Passing byte array between C++ and C# ByRef raises AccessViolationException

后端 未结 1 837
情深已故
情深已故 2020-12-29 15:42

I am trying to create a Win32 DLL exposes some functions which are called in C# as follows

__declspec(dllexport) int GetData(unsigned char* *data, int* size)         


        
相关标签:
1条回答
  • 2020-12-29 16:02

    You are returning an array allocated by a call to C++ new and hoping that the marshaler will turn it into a C# byte[]. That won't happen.

    You'll need to pass a pointer by reference and then marshal it by hand. Your p/invoke should look like this:

    [DllImport("MyDll.dll")]
    static extern int GetData(out IntPtr data, out int size);
    

    When the function returns data will point to the array and you can read the contents using the Marshal class. I guess you would copy it to a new byte array.

    var arr = new byte[size];
    Marshal.Copy(data, arr, 0, size);
    

    Some other points:

    1. The calling conventions do not match. The native side is cdecl and the managed is stdcall.
    2. You'll need to export a deallocator to delete the memory returned by the native function. Consider a re-design where the caller allocates the buffer.
    0 讨论(0)
提交回复
热议问题