欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來到入門教程網(wǎng)!

C#教程

當(dāng)前位置:主頁 > 軟件編程 > C#教程 >

C#調(diào)用C++DLL傳遞結(jié)構(gòu)體數(shù)組的終極解決方案

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C#教程|點(diǎn)擊: 次

C#調(diào)用C++DLL傳遞結(jié)構(gòu)體數(shù)組的終極解決方案

在項(xiàng)目開發(fā)時,要調(diào)用C++封裝的DLL,普通的類型C#上一般都對應(yīng),只要用DllImport傳入從DLL中引入函數(shù)就可以了。但是當(dāng)傳遞的是結(jié)構(gòu)體、結(jié)構(gòu)體數(shù)組或者結(jié)構(gòu)體指針的時候,就會發(fā)現(xiàn)C#上沒有類型可以對應(yīng)。這時怎么辦,第一反應(yīng)是C#也定義結(jié)構(gòu)體,然后當(dāng)成參數(shù)傳弟。然而,當(dāng)我們定義完一個結(jié)構(gòu)體后想傳遞參數(shù)進(jìn)去時,會拋異常,或者是傳入了結(jié)構(gòu)體,但是返回值卻不是我們想要的,經(jīng)過調(diào)試跟蹤后發(fā)現(xiàn),那些值壓根沒有改變過,代碼如下。

[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); 
      } 
    } 

后來,經(jīng)過查找資料,有文提到對于C#是屬于托管內(nèi)存,現(xiàn)在要傳遞結(jié)構(gòu)體數(shù)組,是屬性非托管內(nèi)存,必須要用Marsh指定空間,然后再傳遞。于是將結(jié)構(gòu)體變更如下。

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;          
 
   }; 

但是經(jīng)過這樣的改進(jìn)后,運(yùn)行結(jié)果依然不理想,值要么出錯,要么沒有被改變。這究竟是什么原因?不斷的搜資料,終于看到了一篇,里面提到結(jié)構(gòu)體的傳遞,有的可以如上面所做,但有的卻不行,特別是當(dāng)參數(shù)在C++中是結(jié)構(gòu)體指針或者結(jié)構(gòu)體數(shù)組指針時,在C#調(diào)用的地方也要用指針來對應(yīng),后面改進(jìn)出如下代碼。

[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); 
    } 
  } 

要注意的是,這時接口已經(jīng)改成IntPtr了。通過以上方式,終于把結(jié)構(gòu)體數(shù)組給傳進(jìn)去了。不過,這里要注意一點(diǎn),不同的編譯器對結(jié)構(gòu)體的大小會不一定,比如上面的結(jié)構(gòu)體

在BCB中如果沒有字節(jié)對齊的話,有時會比一般的結(jié)構(gòu)體大小多出2兩個字節(jié)。因?yàn)锽CB默認(rèn)的是2字節(jié)排序,而VC是默認(rèn)1 個字節(jié)排序。要解決該問題,要么在BCB的結(jié)構(gòu)體中增加字節(jié)對齊,要么在C#中多開兩個字節(jié)(如果有多的話)。字節(jié)對齊代碼如下。

#pragma pack(push,1) 
  struct Info 
{ 
  int OrderNO; 
       
  char UniqueCode[32]; 
 
  float CpuPercent; 
}; 
#pragma pack(pop) 

用Marsh.AllocHGlobal為結(jié)構(gòu)體指針開辟內(nèi)存空間,目的就是轉(zhuǎn)變化非托管內(nèi)存,那么如果不用Marsh.AllocHGlobal,還有沒有其他的方式呢?

其實(shí),不論C++中的是指針還是數(shù)組,最終在內(nèi)存中還是一個一個字節(jié)存儲的,也就是說,最終是以一維的字節(jié)數(shù)組形式展現(xiàn)的,所以我們?nèi)绻_一個等大小的一維數(shù)組,那是否就可以了呢?答案是可以的,下面給出了實(shí)現(xiàn)。

[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 

對于實(shí)在想不到要怎么傳數(shù)據(jù)的時候,可以考慮byte數(shù)組來傳(即便是整型也可以,只要是開辟4字節(jié)(在32位下)),只要開的長度對應(yīng)的上,在拿到數(shù)據(jù)后,要按類型規(guī)則轉(zhuǎn)換成所要的數(shù)據(jù),一般都能達(dá)到目的。

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

上一篇:C# salt+hash 加密

欄    目:C#教程

下一篇:C# 文件下載之?dāng)帱c(diǎn)續(xù)傳實(shí)現(xiàn)代碼

本文標(biāo)題:C#調(diào)用C++DLL傳遞結(jié)構(gòu)體數(shù)組的終極解決方案

本文地址:http://mengdiqiu.com.cn/a1/C_jiaocheng/6007.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有