源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2020-06-02 21:03 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:C#访问C++动态分配的数组指针(实例讲解)
项目中遇到C#调用C++算法库的情况,C++内部运算结果返回矩形坐标数组(事先长度未知且不可预计),下面方法适用于访问C++内部分配的任何结构体类型数组。当时想当然的用ref array[]传递参数,能计算能分配,但是在C#里只得到arr长度是1,无法访问后续数组Item。 [b]C++[/b] [b]接口示例:[/b]
void Call(int *count, Rect **arr)
{
 //…..
 //重新Malloc一段内存,指针复制给入参,外部调用前并不知道长度,另外提供接口Free内存
 //….
}
[b]结构体:[/b]
Struct Rect
{
int x;
int y;
int width;
int height;
};
[b]C#:[/b] [b]结构体:[/b]
Struct Rect
{
public int x;
public int y;
public int width;
public int height;
}
[b]外部DLL方法声明:[/b]
 [DllImport("xxx.dll", EntryPoint = "Call", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
 public static extern void Call(
     ref int count,
     ref IntPtr pArray);
[b]方法调用:[/b]
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));
}
参考链接:[b][url=http://www.1sucai.cn/article/130602.htm]基于C#调用c++Dll结构体数组指针的问题详解[/url][/b] 以上这篇C#访问C++动态分配的数组指针(实例讲解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部