P调用返回指针的C函数 [英] PInvoke C function that return pointer
本文介绍了P调用返回指针的C函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的C函数:
Hi,
I have a C function like this:
double* foo() // function return array of 10 double
{
double* matrix = (double *)malloc(10 * sizeof(double));
return matrix;
}
如何在包装器类中编写?我应该这样做吗?
how can I write in the wrapper class? Should I do that?
[DllImport("...")]
[return: MarshalAs(UnmanagedType..LPArray)]
public static extern double foo();
请告诉我方法.
Please tell me the way.
推荐答案
[DllImport("...")]
public static extern IntPtr foo();
应该管用.然后,如果您知道数组的大小:
Should work. Then if you know the size of the array:
IntPtr result = foo();
double[] arr = new double[10];
Marshal.Copy(result, arr, 0, 10);
如果数组大小不是静态的,则应返回数组大小,如下所示:
If the array size isn''t static, then you should return the size of the array like this:
double* foo(int* size) // function return array of 10 double
{
double* matrix = (double *)malloc(10 * sizeof(double));
*size = 10;
return matrix;
}
并使用:
And use:
[DllImport("...")]
public static extern IntPtr foo(out int size);
...
int size;
IntPtr result = foo(out size);
double[] arr = new double[size];
Marshal.Copy(result, arr, 0, size);
这篇关于P调用返回指针的C函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文