Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

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

I'm trying to pass raw texture data from Texture2D (byte array) to unmanaged C++ code. In C# code array length is about 1,5kk, however in C++ 'sizeof' always returns 8.

C# declaration of native method :

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

C++:

extern "C" {
    __declspec(dllexport) void ProcessData(uint8_t *data) {
        //sizeof(data) is always 8
    }
}

What am I doing wrong? Is there is a way to pass array without additional memory allocation in C++ code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...