C#访问C++动态分配的数组指针
C#访问C++动态分配的数组指针
项目中遇到C#调用C++算法库的情况,C++内部运算结果返回矩形坐标数组(事先长度未知且不可预计),下面方法适用于访问C++内部分配的任何结构体类型数组。当时想当然的用ref array[]传递参数,能计算能分配,但是在C#里只得到arr长度是1,无法访问后续数组Item。
==========================================================================
C++
==========================================================================
接口示例:
1 void Call(int *count, Rect **arr) 2 { 3 //….. 4 //重新Malloc一段内存,指针复制给入参,外部调用前并不知道长度,另外提供接口Free内存 5 //…. 6 }
结构体:
1 Struct Rect 2 { 3 int x; 4 int y; 5 int width; 6 int height; 7 };
========================================================================
C#:
========================================================================
结构体:
1 Struct Rect 2 { 3 public int x; 4 public int y; 5 public int width; 6 public int height; 7 }
外部DLL方法声明:
1 [DllImport("xxx.dll", EntryPoint = "Call", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] 2 public static extern void Call( 3 ref int count, 4 ref IntPtr pArray);
方法调用:
1 IntPtr pArray = IntPtr.Zero; //数组指针 2 int count = 0; 3 Call(ref count, ref pArray); 4 var rects = new Rect[count]; //结果数组 5 for (int i = 0; i < count; i++) 6 { 7 var itemptr = (IntPtr)((Int64)Rect + i * Marshal.SizeOf(typeof(Rect))); //这里有人用的UInt32,我用的时候溢出了,换成Int64 8 rects[i] = (Rect)Marshal.PtrToStructure(itemptr, typeof(Rect)); 9 }
========================================================================
参考链接:http://blog.csdn.net/wumuzhizi/article/details/48180167
此外,如果数组是int,long,double,float这类基础类型,就方便多了,直接调用Marshal.Copy(pArray, rects, 0, count)就好了。