C#调C++DLL C++参数为二级指针数组,C#如何对应相关指针参数
C#调C++DLL C++参数为二级指针数组,C#怎么对应相关指针参数
extern"C"_declspec(dllexport)void Fun(double **K){
K=(double **)malloc(sizeof(double *)*3);
for(int i=0;i<3;i++)
K[i]=(double *)malloc(sizeof(double)*2);
for(int i=0;i<3;i++)
for(int j=0;j<2;j++)
K[i][j]=j+1;
}
C#
[DllImport("C_POint.dll", EntryPoint = "Fun", CallingConvention = CallingConvention.Cdecl)]
public static extern void Fun( double [,]a);
static void Main(string[] args)
{
double[,] a = new double [3,2];
CPPDLL.Fun( a);//DLL 调用
for (int i = 0; i < 3; i++)
for (int j = 0; j < 2; j++)
Console.Write(a[i, j]);
}
关键是C#中 public static extern void Fun( double [,]a); 函数声明及调用 CPPDLL.Fun( a);//DLL 调用
这里怎么设置C# 相对应的指针数组××K呢????
------解决思路----------------------
首先,你的代码本身就有问题,要想把k传出来,得用double*** k,按如下方式修改代码,我已经测试可以正常使用,还有,关于C#调用C++函数你可以打开VS的启用本机代码调试功能,这样直接就能从C#代码单步步入C++代码,问题一眼就看出来了
extern"C"_declspec(dllexport)void Fun(double **K){
K=(double **)malloc(sizeof(double *)*3);
for(int i=0;i<3;i++)
K[i]=(double *)malloc(sizeof(double)*2);
for(int i=0;i<3;i++)
for(int j=0;j<2;j++)
K[i][j]=j+1;
}
C#
[DllImport("C_POint.dll", EntryPoint = "Fun", CallingConvention = CallingConvention.Cdecl)]
public static extern void Fun( double [,]a);
static void Main(string[] args)
{
double[,] a = new double [3,2];
CPPDLL.Fun( a);//DLL 调用
for (int i = 0; i < 3; i++)
for (int j = 0; j < 2; j++)
Console.Write(a[i, j]);
}
关键是C#中 public static extern void Fun( double [,]a); 函数声明及调用 CPPDLL.Fun( a);//DLL 调用
这里怎么设置C# 相对应的指针数组××K呢????
------解决思路----------------------
首先,你的代码本身就有问题,要想把k传出来,得用double*** k,按如下方式修改代码,我已经测试可以正常使用,还有,关于C#调用C++函数你可以打开VS的启用本机代码调试功能,这样直接就能从C#代码单步步入C++代码,问题一眼就看出来了
#define DLLEXPORT EXTERN_C __declspec(dllexport)
DLLEXPORT void Fun(double*** K)
{
*K=(double **)malloc(sizeof(double *)*3);
for(int i=0;i<3;i++)
(*K)[i]=(double *)malloc(sizeof(double)*2);
for(int i=0;i<3;i++)
for(int j=0;j<2;j++)
(*K)[i][j]=j+1;
}
[DllImport("DoubleTest", EntryPoint = "Fun", CallingConvention = CallingConvention.Cdecl)]
public unsafe static extern void Fun(double*** k);
private unsafe void button1_Click(object sender, EventArgs e)
{
double*** a = (double***)Marshal.AllocHGlobal(IntPtr.Size);
Fun(a);
for (int i = 0; i < 3; i++)
for (int j = 0; j < 2; j++)
richTextBox1.AppendText(*(*(*a+i)+j) + Environment.NewLine);
}