项目中遇到C#调用C++算法库的情况,C++内部运算结果返回矩形坐标数组(事先长度未知且不可预计),下面方法适用于访问C++内部分配的任何结构体类型数组。当时想当然的用ref array[]传递参数,能计算能分配,但是在C#里只得到arr长度是1,无法访问后续数组Item。
C++
接口示例:
void Call(int *count, Rect **arr){
//….. //重新Malloc一段内存,指针复制给入参,外部调用前并不知道长度,另外提供接口Free内存 //….}
结构体:
Struct Rect{
int x;
int y;
int width;
int height;
}
;
C#:
结构体:
Struct Rect{
public int x;
public int y;
public int width;
public int height;
}
外部DLL方法声明:
[DllImport("xxx.dll", EntryPoint = "Call", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern void Call( ref int count, ref IntPtr pArray);
方法调用:
IntPtr pArray = IntPtr.Zero;
//数组指针int count = 0;
Call(ref count, ref pArray);
var rects = new Rect[count];
//结果数组for (int i = 0;
i < count;
i++){
var itemptr = (IntPtr)((Int64)Rect + i * Marshal.SizeOf(typeof(Rect)));
//这里有人用的UInt32,我用的时候溢出了,换成Int64rects[i] = (Rect)Marshal.PtrToStructure(itemptr, typeof(Rect));
}
以上这篇C#访问C++动态分配的数组指针(实例讲解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
- 深入解析C++中的指针数组与指向指针的指针
- 动态数组C++实现方法(分享)
- C#中动态数组用法实例