Pass byte array from Unity C# to C++ plugin

Few things you need to do with your current code:

1.You have to send the size of the array to the C++ plugin in another parameter as UnholySheep mentioned.

2.You also have to pin the array before sending it to the C++ side. This is done with the fixed keyword or GCHandle.Alloc function.

3.If the C++ function has a void return type, your C# function should also have the void return type.

Below is a corrected version of your code. No additional memory allocation is performed.

C#:

[DllImport("LibName", CallingConvention = CallingConvention.Cdecl)]
static extern void ProcessData(IntPtr data, int size);

public unsafe void ProcessData(byte[] data, int size)
{
    //Pin Memory
    fixed (byte* p = data)
    {
        ProcessData((IntPtr)p, size);
    }
}

C++:

extern "C" 
{
    __declspec(dllexport) void ProcessData(unsigned char* data, int size) 
    {
        //sizeof(data) is always 8
    }
}

Leave a Comment