简体   繁体   English

将字节数组从Unity C#传递到C ++插件

[英]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. 我正在尝试将原始纹理数据从Texture2D(字节数组)传递给非托管C ++代码。 In C# code array length is about 1,5kk, however in C++ 'sizeof' always returns 8. 在C#代码数组中,长度约为1,5kk,但是在C ++中,“ sizeof”始终返回8。

C# declaration of native method : 原生方法的C#声明:

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

C++: 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? 有没有一种方法可以在C ++代码中传递数组而无需分配额外的内存?

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. 1。您必须使用UnholySheep提到的另一个参数将数组的大小发送到C ++插件。

2 .You also have to pin the array before sending it to the C++ side. 2。在将数组发送到C ++端之前,还必须将其固定。 This is done with the fixed keyword or GCHandle.Alloc function. 这是通过fixed关键字或GCHandle.Alloc函数完成的。

3 .If the C++ function has a void return type, your C# function should also have the void return type. 3。如果C ++函数具有void返回类型,则您的C#函数也应具有void返回类型。

Below is a corrected version of your code. 下面是您的代码的更正版本。 No additional memory allocation is performed. 不执行其他内存分配。

C#: 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++: C ++:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM