当前位置: 移动技术网 > IT编程>开发语言>c# > C#调用C++DLL传递结构体数组的终极解决方案

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

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

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

[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指定空间,然后再传递。于是将结构体变更如下。

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#调用的地方也要用指针来对应,后面改进出如下代码。

[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#中多开两个字节(如果有多的话)。字节对齐代码如下。

#pragma pack(push,1) 
  struct info 
{ 
  int orderno; 
       
  char uniquecode[32]; 
 
  float cpupercent; 
}; 
#pragma pack(pop) 

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

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

[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位下)),只要开的长度对应的上,在拿到数据后,要按类型规则转换成所要的数据,一般都能达到目的。

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网