从 C++ 获取浮点数组到 C#
Getting float array from C++ to C#
我在 C++ 函数中有 float 数组。
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++ 代码中的这一行:
float *array = new float[20];
创建一个新数组,您可以在 C++ 中对其进行操作。然后将 returns 控制到 C#,C# 拥有自己的数组并且仍然没有改变。你为什么不写入你得到的数组?
问题是您在参数结果上使用了赋值运算符,这会阻止数据传输到 return 上的 C# 数组。
使用以下 C++ 示例:
void z(int * x)
{
x = new int(4);
}
int main()
{
int * x = new int(-2);
z(x);
cout<<*x<<endl;
}
此输出是 -2 而不是 4,因为您在参数上使用了赋值运算符。
正如 UnholySheep 和 nvoigt 所说,
result = array;
覆盖传递指针的地址,使您失去对调用函数的引用。
直接写入您的参数应该可以解决这个问题。
result[i] = 25;
此外,您实际上不必在 C# 中使用指针。
您实际上可以执行以下操作:
像这样声明您的导入:
private static extern void bleplugin_GetGolfResult (float arr[]);
那么你可以这样称呼它:
float arr = new float[20];
bleplugin_GetGolfResult(arr);
我在 C++ 函数中有 float 数组。
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++ 代码中的这一行:
float *array = new float[20];
创建一个新数组,您可以在 C++ 中对其进行操作。然后将 returns 控制到 C#,C# 拥有自己的数组并且仍然没有改变。你为什么不写入你得到的数组?
问题是您在参数结果上使用了赋值运算符,这会阻止数据传输到 return 上的 C# 数组。
使用以下 C++ 示例:
void z(int * x)
{
x = new int(4);
}
int main()
{
int * x = new int(-2);
z(x);
cout<<*x<<endl;
}
此输出是 -2 而不是 4,因为您在参数上使用了赋值运算符。
正如 UnholySheep 和 nvoigt 所说,
result = array;
覆盖传递指针的地址,使您失去对调用函数的引用。
直接写入您的参数应该可以解决这个问题。
result[i] = 25;
此外,您实际上不必在 C# 中使用指针。 您实际上可以执行以下操作:
像这样声明您的导入:
private static extern void bleplugin_GetGolfResult (float arr[]);
那么你可以这样称呼它:
float arr = new float[20];
bleplugin_GetGolfResult(arr);