【问题标题】:Unity, c++ native plugin mismatching byte arrayUnity,C++原生插件不匹配字节数组
【发布时间】:2018-04-26 15:06:33
【问题描述】:

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

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

在我的 C# 端我有电话

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

出于某种原因,尽管我在这两个调用之间存在不匹配,即如果在我的 C++ 中检查作为输出得到的数组的大小:16777216(针对我的具体情况)。

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

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

byte[] outputBuffer = getCPPOutput();

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

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

【问题讨论】:

  • 您是否使用.size.max_size 在C++ 中检查向量的大小?向量后备存储可能比向量中的实际数据大,尽管很难想象它会大得多。
  • @RonBeyer 我正在使用.size

标签: c# c++ unity3d


【解决方案1】:

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

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

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 变量声明。如果在该函数中将其声明为局部变量,则它在堆栈上,您必须使用 new 关键字动态分配新数组,并在 C# 上接收到它后使用 delete 关键字创建另一个函数来释放它边。除非将数组声明为 static 对象或使用 new 关键字动态分配,否则您不能在堆栈上返回数组。

【讨论】:

  • 我的问题更多是关于“我有这个问题,除此之外还有什么问题”。
  • 但是我明白你的意思,我应该在 C# 端预先分配输出并填充该数组。你可能是对的,我应该这样做,我只从 C# -> C++ 中阅读了我的另一个问题的答案,反之亦然。
  • “嗯,我的问题更多是关于“我有这个问题,还有什么问题”” 返回类型不匹配,这在第一句中提到这个答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-11
  • 2015-08-26
  • 1970-01-01
相关资源
最近更新 更多