首页 > 编程技术 > csharp

C#访问C++动态分配的数组指针(实例讲解)

发布时间:2020-6-25 11:17

项目中遇到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,我用的时候溢出了,换成Int64
rects[i] = (Rect)Marshal.PtrToStructure(itemptr, typeof(Rect));
}

参考链接:基于C#调用c++Dll结构体数组指针的问题详解

以上这篇C#访问C++动态分配的数组指针(实例讲解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持猪先飞。

标签:[!--infotagslink--]

您可能感兴趣的文章: