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

作者:Wood_J 时间:2021-08-20 10:34:27 

项目中遇到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结构体数组指针的问题详解

来源:http://www.cnblogs.com/woodj/archive/2017/12/13/woodj.html

标签:C#,访问,C++,动态分配,数组,指针
0
投稿

猜你喜欢

  • Spring 4.0新功能:@Conditional注解详细介绍

    2022-01-19 06:37:35
  • Java8 CompletableFuture 异步多线程的实现

    2023-07-21 08:07:15
  • java dump文件怎么生成和分析-JMAP用法详解

    2021-06-03 23:59:43
  • C#中+=是什么意思及+=的用法

    2023-07-11 23:25:31
  • Android使用GestureOverlayView控件实现手势识别

    2023-03-02 08:46:26
  • SpringCloud Eureka服务治理之服务注册服务发现

    2021-12-27 15:07:16
  • C#显示文件夹下所有图片文件的方法

    2021-11-25 23:50:10
  • C#泛型用法实例分析

    2021-10-16 14:01:49
  • Spring Cloud 配置中心内容加密的配置方法

    2023-02-11 09:05:15
  • Java中关键字synchronized的使用方法详解

    2022-04-14 06:18:54
  • 用SpringBoot+Vue+uniapp小程序实现在线房屋装修管理系统

    2023-11-12 04:10:48
  • Java命令设计模式详解

    2022-07-14 04:38:31
  • springboot中的静态资源加载顺序优先级

    2023-08-24 11:12:31
  • java ArrayList和Vector的区别详解

    2023-03-08 14:47:05
  • Visual C#中如何使用IComparable和IComparer接口

    2021-12-17 20:01:02
  • Android开发实现控件双击事件的监听接口封装类

    2023-02-15 00:56:18
  • C++中的异常处理机制详解

    2023-04-16 16:01:10
  • Android实现腾讯新闻的新闻类别导航效果

    2023-07-29 04:17:46
  • WPF弹出自定义窗口的方法

    2023-10-18 20:52:04
  • 用JAVA 设计生成二维码详细教程

    2021-05-29 05:48:29
  • asp之家 软件编程 m.aspxhome.com