将字节数组从Unity C#传递到C ++插件 [英] Pass byte array from Unity C# to C++ plugin
问题描述
我正在尝试将原始纹理数据从Texture2D(字节数组)传递给非托管C ++代码.在C#代码数组中,长度大约为1,5kk,但是在C ++中,"sizeof"总是返回8.
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#声明:
[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
}
}
我做错了什么?有没有一种方法可以在C ++代码中不增加内存分配的情况下传递数组?
What am I doing wrong? Is there is a way to pass array without additional memory allocation in C++ code?
推荐答案
与当前代码无关的几件事:
Few things you need to do with your current code:
1 .您必须使用 UnholySheep>在另一个参数中将数组的大小发送到C ++插件. 提到.
1.You have to send the size of the array to the C++ plugin in another parameter as UnholySheep mentioned.
2 .您还必须固定数组,然后再将其发送到C ++端.这是通过fixed
关键字或GCHandle.Alloc
函数完成的.
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 .如果C ++函数具有void返回类型,则您的C#函数也应具有void返回类型.
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
}
}
这篇关于将字节数组从Unity C#传递到C ++插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!