SafeArrayPutElement method throws System.AccessViolationException

吃可爱长大的小学妹 提交于 2019-12-11 14:22:10

问题


I am trying to pass an array of ints from C# to C++/CLI. Here's my code:

// SafeArrayTesting_PlusPlus.cpp  
#include "stdafx.h"  
#include <comdef.h>  
using namespace System;  
namespace SafeArrayTesting_PlusPlus  
{   
    public ref class MyCppClass  
    {       
       public:  
         MyCppClass();  
         ~MyCppClass();  
         void SetMyInts(array<int>^ myInts);  
     };  

     MyCppClass::MyCppClass(){}  
    MyCppClass::~MyCppClass(){}  

    void MyCppClass::SetMyInts(array<int>^ myInts)  
    {  
        // Create safearray
        SAFEARRAY  *safeArrayPointer;
        SAFEARRAYBOUND arrayDim[1];    // one dimensional array
        arrayDim[0].lLbound= 0;
        arrayDim[0].cElements= myInts->Length;
        safeArrayPointer = SafeArrayCreate(VT_UNKNOWN,1,arrayDim);

        // copy ints to safearray
        for (long lo= 0; lo < myInts->Length; lo++)
        {           
            cli::pin_ptr<int> pinnedIntPointer = &(myInts[lo]);
            SafeArrayPutElement(  
                safeArrayPointer,  
                &lo,  
                static_cast<void*> (pinnedIntPointer)); // line XX
        }

        // do something with the safearray here
    }
}   

// SafeArrayTesting_Main.cs
using SafeArrayTesting_PlusPlus;

namespace SafeArrayTesting_Main
{
    class SafeArrayTesting_Main
    {
        static void Main()
        {
            var myCppClass = new MyCppClass();
            myCppClass.SetMyInts(new[]{42});
        }
    }
}

When I run this, line XX throws the following exception:

System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

I have a feeling that I'm doing something basically wrong with the SafeArrayPutElement method. Can you spot the error?

(By the way, I have asked a more complex variation of this question at Passing an array of interfaces from C# to C++/CLI . I think the difference is big enough to warrant two separate questions.)


回答1:


    safeArrayPointer = SafeArrayCreate(VT_UNKNOWN,1,arrayDim);

That creates an array of IUnknown interface pointers. SafeArrayPut() makes sure to increase the reference count of the interface pointer by calling IUnknown::AddRef() since it stores a copy of the pointer in the array.

You can see how that goes kaboom. Create an array of integers instead. Fix:

    safeArrayPointer = SafeArrayCreate(VT_I4,1,arrayDim);


来源:https://stackoverflow.com/questions/3434926/safearrayputelement-method-throws-system-accessviolationexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!