gpt4 book ai didi

c# - Unity,c++ native 插件不匹配的字节数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:06:06 25 4
gpt4 key购买 nike

在我的 C++ 原生插件中我有一个调用

vector<unsigned char> getCPPOutput() {
return some_vector;
}

在我的 C# 端我有调用

[DllImport("MySharedObj")]
static extern byte[] getCPPOutput();

由于某些原因,虽然我在这两个调用之间存在不匹配,即如果在我的 C++ 中我检查我作为输出获得的数组的大小:16777216(对于我的特定情况)。

当我检查字节数组的大小时,我得到:170409961

C# 上的调用非常简单,类似于:

byte[] outputBuffer = getCPPOutput();

没有任何预分配。在调用该函数之前我需要做些什么吗?

我根本不是 C# 专家,我可能漏掉了一些非常愚蠢的东西。

最佳答案

您的返回类型是 byte[]在 C# 中但是 vector<unsigned char>在 C++ 中。这些不匹配。在你的其他问题中,我们鼓励你填充数组而不是返回它,但你仍然想返回一个数组,这是如何做到的:

转换 Vector数组然后返回它。 C++ 返回类型应为 char* C# 返回类型应该是 IntPtr .此外,您需要一种方法来告诉 C# 数组的大小。你可以用一个参数来做到这一点。在 C# 端,您必须使用该参数返回的大小再次创建新数组。在此之后,使用 Marshal.CopyIntPtr 复制数据到那个新数组。

C++:

char* getCPPOutput(int* outValue)
{
//Convert the Vector to array
char* vArrray = &some_vector[0];
*outValue = some_vector.size();
return vArrray;
}

C#:

[DllImport("MySharedObj", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr getCPPOutput(out int outValue);


//Test
void Start()
{
int size = 0;

//Call and return the pointer
IntPtr returnedPtr = getCPPOutput(out size);

//Create new Variable to Store the result
byte[] returnedResult = new byte[size];

//Copy from result pointer to the C# variable
Marshal.Copy(returnedPtr, returnedResult, 0, size);


//The returned value is saved in the returnedResult variable

}

注意你的 C++ 代码:

我没看到你的some_vector变量声明。如果 this 在该函数中被声明为局部变量,那么它就在堆栈上,您必须使用 new 动态分配新数组。关键字并创建另一个函数以使用 delete 释放它在 C# 端收到关键字后。除非声明为 static,否则不能返回堆栈上的数组对象或使用 new 动态分配关键字。

关于c# - Unity,c++ native 插件不匹配的字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50046392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com