PInvoke返回具有二维数组的结构
问题描述:
我有在 c ++ Win32 DLL如下:
I have struct which is defined in c++ Win32 DLL like the following:
typedef struct matrix
{
double** data;
int m;
int n;
} Matrix;
有一个功能:
Matrix getMatrix(void);
Matrix getMatrix()
{
Matrix mat;
mat.m = 2;
mat.n = 2;
mat.data = (double**) malloc (sizeof(double*) * 4);
mat.data[0] = (double* ) malloc (sizeof(double) * 2);
mat.data[1] = (double* ) malloc (sizeof(double) * 2);
mat.data [0][0]=1;
mat.data [0][1]=2;
mat.data [1][0]=3;
mat.data [1][1]=4;
return mat;
}
如果我从C#应用程序中使用 P/Invoke
,如何捕获此函数的返回值
How can I capture the return value of this function If I'm using P/Invoke
from a C# Application
答
我不确定是否可行,但是从内存中:将数据声明为IntPtr并使用它:
I am not sure if it works, but from memory: Declare data as IntPtr and use this :
static double[][] FromNative (IntPtr data, int m,int n)
{
var matrix=new double[m][];
for(int i=0;i<m;i++)
{
matrix[i]=new double[n];
Marshal.Copy(Marshal.ReadIntPtr(data),matrix[i],0,n);
data =(IntPtr)(data.ToInt64()+IntPtr.Size);
}
return matrix;
}