PInvoke返回具有二维数组的结构 [英] PInvoke return struct with two dimensions array

查看:73
本文介绍了PInvoke返回具有二维数组的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在 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;
}

这篇关于PInvoke返回具有二维数组的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆