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位下)),只要開的長度對應的上,在拿到數據后,要按類型規則轉換成所要的數據,一般都能達到目的。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答