将float数组从C ++转换为C#

时间:2017-12-06 14:37:20

标签: c# c++ dllimport

我在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。

可能出现什么问题?

3 个答案:

答案 0 :(得分:3)

C ++代码中的这一行:

float *array = new float[20];

创建一个新数组,您可以在C ++中进行操作。然后控制返回到C#,C#拥有自己的数组并且仍然保持不变。你为什么不写你得到的数组呢?

答案 1 :(得分:2)

正如UnholySheep和nvoigt所说,

result = array;

覆盖传递指针的地址,使您失去对调用函数的引用。

直接写入参数应解决此问题。

result[i] = 25;

此外,你实际上不必在c#中使用指针。 您实际上可以执行以下操作:

按照以下方式声明您的导入:

private static extern void bleplugin_GetGolfResult (float arr[]);

然后你可以这样称呼它:

float arr = new float[20];
bleplugin_GetGolfResult(arr);

答案 2 :(得分:0)

问题是您在参数结果上使用赋值运算符,这会阻止数据在返回时传输到C#数组。

使用以下C ++示例:

void z(int * x)
{
  x = new int(4);
}

int main()
{
  int * x = new int(-2);
  z(x);
  cout<<*x<<endl;
}

此输出为-2而不是4,因为您在参数上使用赋值运算符。