服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C#调用C++DLL传递结构体数组的终极解决方案

C#调用C++DLL传递结构体数组的终极解决方案

2021-12-20 14:41xxdddail C#

这篇文章主要介绍了C#调用C++DLL传递结构体数组的终极解决方案的相关资料,需要的朋友可以参考下

C#调用C++DLL传递结构体数组的终极解决方案

在项目开发时,要调用C++封装的DLL,普通的类型C#上一般都对应,只要用DllImport传入从DLL中引入函数就可以了。但是当传递的是结构体、结构体数组或者结构体指针的时候,就会发现C#上没有类型可以对应。这时怎么办,第一反应是C#也定义结构体,然后当成参数传弟。然而,当我们定义完一个结构体后想传递参数进去时,会抛异常,或者是传入了结构体,但是返回值却不是我们想要的,经过调试跟踪后发现,那些值压根没有改变过,代码如下。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
[DllImport("workStation.dll")]
    private static extern bool fetchInfos(Info[] infos);
    public struct Info
    {
      public int OrderNO;
 
      public byte[] UniqueCode;
 
      public float CpuPercent;         
 
    };
    private void buttonTest_Click(object sender, EventArgs e)
    {
      try
      {
      Info[] infos=new Info[128];
        if (fetchInfos(infos))
        {
          MessageBox.Show("Fail");
        }
      else
      {
          string message = "";
          foreach (Info info in infos)
          {
            message += string.Format("OrderNO={0}\r\nUniqueCode={1}\r\nCpu={2}",
                       info.OrderNO,
                       Encoding.UTF8.GetString(info.UniqueCode),
                       info.CpuPercent
                       );
          }
          MessageBox.Show(message);
      }
      }
      catch (System.Exception ex)
      {
        MessageBox.Show(ex.Message);
      }
    }

后来,经过查找资料,有文提到对于C#是属于托管内存,现在要传递结构体数组,是属性非托管内存,必须要用Marsh指定空间,然后再传递。于是将结构体变更如下。

?
1
2
3
4
5
6
7
8
9
10
11
StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
   public struct Info
   {
     public int OrderNO;
 
     [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
     public byte[] UniqueCode;
 
     public float CpuPercent;         
 
   };

但是经过这样的改进后,运行结果依然不理想,值要么出错,要么没有被改变。这究竟是什么原因?不断的搜资料,终于看到了一篇,里面提到结构体的传递,有的可以如上面所做,但有的却不行,特别是当参数在C++中是结构体指针或者结构体数组指针时,在C#调用的地方也要用指针来对应,后面改进出如下代码。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
[DllImport("workStation.dll")]
  private static extern bool fetchInfos(IntPtr infosIntPtr);
  [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
  public struct Info
  {
    public int OrderNO;
 
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
    public byte[] UniqueCode;
 
    public float CpuPercent;
 
  };
  private void buttonTest_Click(object sender, EventArgs e)
  {
    try
    {
      int workStationCount = 128;
      int size = Marshal.SizeOf(typeof(Info));
      IntPtr infosIntptr = Marshal.AllocHGlobal(size * workStationCount);
      Info[] infos = new Info[workStationCount];
      if (fetchInfos(infosIntptr))
      {
        MessageBox.Show("Fail");
        return;
      }
      for (int inkIndex = 0; inkIndex < workStationCount; inkIndex++)
      {
        IntPtr ptr = (IntPtr)((UInt32)infosIntptr + inkIndex * size);
        infos[inkIndex] = (Info)Marshal.PtrToStructure(ptr, typeof(Info));
      }
 
      Marshal.FreeHGlobal(infosIntptr);
 
      string message = "";
      foreach (Info info in infos)
      {
        message += string.Format("OrderNO={0}\r\nUniqueCode={1}\r\nCpu={2}",
                    info.OrderNO,
                    Encoding.UTF8.GetString(info.UniqueCode),
                    info.CpuPercent
                    );
      }
      MessageBox.Show(message);
 
    }
    catch (System.Exception ex)
    {
      MessageBox.Show(ex.Message);
    }
  }

要注意的是,这时接口已经改成IntPtr了。通过以上方式,终于把结构体数组给传进去了。不过,这里要注意一点,不同的编译器对结构体的大小会不一定,比如上面的结构体

在BCB中如果没有字节对齐的话,有时会比一般的结构体大小多出2两个字节。因为BCB默认的是2字节排序,而VC是默认1 个字节排序。要解决该问题,要么在BCB的结构体中增加字节对齐,要么在C#中多开两个字节(如果有多的话)。字节对齐代码如下。

?
1
2
3
4
5
6
7
8
9
10
#pragma pack(push,1)
  struct Info
{
  int OrderNO;
       
  char UniqueCode[32];
 
  float CpuPercent;
};
#pragma pack(pop)

用Marsh.AllocHGlobal为结构体指针开辟内存空间,目的就是转变化非托管内存,那么如果不用Marsh.AllocHGlobal,还有没有其他的方式呢?

其实,不论C++中的是指针还是数组,最终在内存中还是一个一个字节存储的,也就是说,最终是以一维的字节数组形式展现的,所以我们如果开一个等大小的一维数组,那是否就可以了呢?答案是可以的,下面给出了实现。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
[DllImport("workStation.dll")]
    private static extern bool fetchInfos(IntPtr infosIntPtr);
    [DllImport("workStation.dll")]
    private static extern bool fetchInfos(byte[] infos);
    [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
    public struct Info
    {
      public int OrderNO;
 
      [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
      public byte[] UniqueCode;
 
      public float CpuPercent;
 
    };
 
   
    private void buttonTest_Click(object sender, EventArgs e)
    {
      try
      {
        int count = 128;
        int size = Marshal.SizeOf(typeof(Info));
        byte[] inkInfosBytes = new byte[count * size];        
        if (fetchInfos(inkInfosBytes))
        {
          MessageBox.Show("Fail");
          return;
        }
        Info[] infos = new Info[count];
        for (int inkIndex = 0; inkIndex < count; inkIndex++)
        {
          byte[] inkInfoBytes = new byte[size];
          Array.Copy(inkInfosBytes, inkIndex * size, inkInfoBytes, 0, size);
          infos[inkIndex] = (Info)bytesToStruct(inkInfoBytes, typeof(Info));
        }
 
        string message = "";
        foreach (Info info in infos)
        {
          message += string.Format("OrderNO={0}\r\nUniqueCode={1}\r\nCpu={2}",
                      info.OrderNO,
                      Encoding.UTF8.GetString(info.UniqueCode),
                      info.CpuPercent
                      );
        }
        MessageBox.Show(message);
 
      }
      catch (System.Exception ex)
      {
        MessageBox.Show(ex.Message);
      }
    }
 
    #region bytesToStruct
    /// <summary>
    /// Byte array to struct or classs.
    /// </summary>
    /// <param name=”bytes”>Byte array</param>
    /// <param name=”type”>Struct type or class type.
    /// Egg:class Human{...};
    /// Human human=new Human();
    /// Type type=human.GetType();</param>
    /// <returns>Destination struct or class.</returns>
    public static object bytesToStruct(byte[] bytes, Type type)
    {
 
      int size = Marshal.SizeOf(type);//Get size of the struct or class.     
      if (bytes.Length < size)
      {
        return null;
      }
      IntPtr structPtr = Marshal.AllocHGlobal(size);//Allocate memory space of the struct or class. 
      Marshal.Copy(bytes, 0, structPtr, size);//Copy byte array to the memory space.
      object obj = Marshal.PtrToStructure(structPtr, type);//Convert memory space to destination struct or class.     
      Marshal.FreeHGlobal(structPtr);//Release memory space.  
      return obj;
    }
    #endregion

对于实在想不到要怎么传数据的时候,可以考虑byte数组来传(即便是整型也可以,只要是开辟4字节(在32位下)),只要开的长度对应的上,在拿到数据后,要按类型规则转换成所要的数据,一般都能达到目的。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://blog.csdn.net/xxdddail/article/details/11781003

延伸 · 阅读

精彩推荐
  • C#三十分钟快速掌握C# 6.0知识点

    三十分钟快速掌握C# 6.0知识点

    这篇文章主要介绍了C# 6.0的相关知识点,文中介绍的非常详细,通过这篇文字可以让大家在三十分钟内快速的掌握C# 6.0,需要的朋友可以参考借鉴,下面来...

    雨夜潇湘8272021-12-28
  • C#C#微信公众号与订阅号接口开发示例代码

    C#微信公众号与订阅号接口开发示例代码

    这篇文章主要介绍了C#微信公众号与订阅号接口开发示例代码,结合实例形式简单分析了C#针对微信接口的调用与处理技巧,需要的朋友可以参考下...

    smartsmile20127762021-11-25
  • C#VS2012 程序打包部署图文详解

    VS2012 程序打包部署图文详解

    VS2012虽然没有集成打包工具,但它为我们提供了下载的端口,需要我们手动安装一个插件InstallShield。网上有很多第三方的打包工具,但为什么偏要使用微软...

    张信秀7712021-12-15
  • C#SQLite在C#中的安装与操作技巧

    SQLite在C#中的安装与操作技巧

    SQLite,是一款轻型的数据库,用于本地的数据储存。其优点有很多,下面通过本文给大家介绍SQLite在C#中的安装与操作技巧,感兴趣的的朋友参考下吧...

    蓝曈魅11162022-01-20
  • C#深入理解C#的数组

    深入理解C#的数组

    本篇文章主要介绍了C#的数组,数组是一种数据结构,详细的介绍了数组的声明和访问等,有兴趣的可以了解一下。...

    佳园9492021-12-10
  • C#如何使用C#将Tensorflow训练的.pb文件用在生产环境详解

    如何使用C#将Tensorflow训练的.pb文件用在生产环境详解

    这篇文章主要给大家介绍了关于如何使用C#将Tensorflow训练的.pb文件用在生产环境的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴...

    bbird201811792022-03-05
  • C#C#设计模式之Strategy策略模式解决007大破密码危机问题示例

    C#设计模式之Strategy策略模式解决007大破密码危机问题示例

    这篇文章主要介绍了C#设计模式之Strategy策略模式解决007大破密码危机问题,简单描述了策略模式的定义并结合加密解密算法实例分析了C#策略模式的具体使用...

    GhostRider10972022-01-21
  • C#利用C#实现网络爬虫

    利用C#实现网络爬虫

    这篇文章主要介绍了利用C#实现网络爬虫,完整的介绍了C#实现网络爬虫详细过程,感兴趣的小伙伴们可以参考一下...

    C#教程网11852021-11-16