将字节数组从 Unity C# 传递给 C++ 插件 [英] Pass byte array from Unity C# to C++ plugin

查看:48
本文介绍了将字节数组从 Unity C# 传递给 C++ 插件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将原始纹理数据从 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.您必须在另一个参数中将数组的大小发送到 C++ 插件作为 UnholySheep 提到.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆