【发布时间】:2017-12-06 14:37:20
【问题描述】:
我在 C++ 函数中有浮点数组。
C++ 函数
void bleplugin_GetGolfResult(float* result)
{
float *array = new float[20];
for(int i=0; i < 20; i++)
array[i]= 25;
result = array;
//DEBUG PRINTING1
for(int i=0; i < 20; i++)
cout << result[i] << endl;//Here is correct
return;
}
C#内部
[DllImport ("__Internal")]
private static unsafe extern void bleplugin_GetGolfResult (float* result);
public static unsafe float[] result = new float[20];
public unsafe static void GetGolfREsult(){
fixed (float* ptr_result = result) //or equivalently "... = &f2[0]" address of f2[0]
{
bleplugin_GetGolfResult( ptr_result );
//DEBUG PRINTING2
for(int i = 0; i < 20; i++)
Debug.Log("result data " + ptr_result[i]);
}
return;
}
我从另一个函数调用GetGolfREsult() 来获取结果。
//DEBUG PRINTING1 输出正确。
但是//DEBUG PRINTING2 只产生了 0。
可能出了什么问题?
【问题讨论】:
-
在 C# 方法中为数组赋值的位置在哪里?
-
永远不要在参数上使用赋值运算符
-
result按值传递。因此,分配给它是没有意义的。您的问题在出现任何 C# 代码之前就开始了。您的 C++ 函数目前没有任何用处。你正在超越自己。在尝试从 C++ 调用它之前,请确保您的 C++ 代码有效。而且这里不需要不安全的代码。 -
如果您可以添加有关数组大小的提示(并按照 David 指出的那样修复您的 C++ 代码),您可以使用in this answer 提供的解决方案。