DLL 函数中使用结构体指针作函数参数(C# 调用 C++ 的 DLL)

存在的问题:

问题1:C++ 与 C# 同样定义的结构体在内存布局上有时并不一致;

问题2:C# 中引入了垃圾自动回收机制,其垃圾回收器可能会重新定位指针所指向的结构体变量。

解决方案:

问题1方案:强制指定 C++、C# 结构体的内存布局,使其一致(两者都固定为:结构体的成员按其声明时出现的顺序依次布局,结构体成员的内存对齐为1字节对齐);

为题2方案:C# 调用时将待传递的结构体转化为字节数组,并使用 fixed 语句将该字节数组固定住。

示例代码如下:

1、C++结构体定义:

  #pragma pack(1)
  struct Person
  {
      #define Count_FavoriteNumbers 6
  
      int id;
  
      float favoriteNumbers[Count_FavoriteNumbers];
  
  };
  #pragma pack()        // #pragma pack(1) end

  C++ 导出函数:

  #define DllExport extern "C" __declspec(dllexport)

  DllExport void __stdcall InitPersonInfo_DLL(Person* p_Person)
  {
      p_Person->id = 0;
  
      for (int i = 1; i <= Count_FavoriteNumbers; i++)
      {
          p_Person->favoriteNumbers[i - 1] = 1.11 * i;
      }    
  }

2、C# 结构体定义:

  [StructLayout(LayoutKind.Sequential, Pack = 1)]
      public class Person
      {
          public const int Count_FavoriteNumbers = 6;

          public int id;

          [MarshalAs(UnmanagedType.ByValArray, SizeConst = Count_FavoriteNumbers, ArraySubType = UnmanagedType.U4)]
          public float[] favoriteNumbers = new float[Count_FavoriteNumbers];  
      }

  C# 调用(WPF窗体程序):

  public partial class MainWindow : Window
  {

    [DllImport("MFCLibrary_ExportFunction.dll", EntryPoint = "InitPersonInfo_DLL")]
          static extern unsafe void InitPersonInfo_DLL(byte* p_Person);
          public unsafe void InitPersonInfo(ref Person person)
          {
              byte[] structBytes = StructToBytes(person);
              fixed (byte* p_Person = &structBytes[0])
              {
                  InitPersonInfo_DLL(p_Person);

                  person = (Person)BytesToStruct(structBytes, person.GetType());
              }

    public MainWindow()
          {
      InitializeComponent();

      Person zhangSan = new Person();
      InitPersonInfo(ref zhangSan);
          }

    #region // 结构体与 byte[] 互转

    // Struct 转换为 byte[]
          public static byte[] StructToBytes(object structure)
          {
              int size = Marshal.SizeOf(structure);
              IntPtr buffer = Marshal.AllocHGlobal(size);

              try
              {
                  Marshal.StructureToPtr(structure, buffer, false);
                  byte[] bytes = new byte[size];
                  Marshal.Copy(buffer, bytes, 0, size);

                  return bytes;
              }
              finally
              {
                  Marshal.FreeHGlobal(buffer);
              }
          }

          // byte[] 转换为 Struct
          public static object BytesToStruct(byte[] bytes, Type strcutType)
          {
              int size = Marshal.SizeOf(strcutType);
              IntPtr buffer = Marshal.AllocHGlobal(size);

              try
              {
                  Marshal.Copy(bytes, 0, buffer, size);

                  return Marshal.PtrToStructure(buffer, strcutType);
              }
              finally
              {
                  Marshal.FreeHGlobal(buffer);
              }
          }
          #endregion

  }

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

c++头脑风暴-多态、虚继承、多重继承内存布局

本篇文章深入分析多态、虚继承、多重继承的内存布局以及实现原理。首先还是看一下思维导图:下面根据这个大纲一步一步的进行深入解析。一、没有虚函数时内存布局是怎样的1.没有虚函数时类的内存布局一个类没有虚函数的时候,其实就是结构体,它的内存布局就是按照成员变量的顺序来的。看如下代码:cppinclude<iostreamusingnamespaces

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )

FLV文件格式

1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.