C#調(diào)用C++DLL傳遞結(jié)構(gòu)體數(shù)組的終極解決方案
C#調(diào)用C++DLL傳遞結(jié)構(gòu)體數(shù)組的終極解決方案
在項(xiàng)目開發(fā)時(shí),要調(diào)用C++封裝的DLL,普通的類型C#上一般都對(duì)應(yīng),只要用DllImport傳入從DLL中引入函數(shù)就可以了。但是當(dāng)傳遞的是結(jié)構(gòu)體、結(jié)構(gòu)體數(shù)組或者結(jié)構(gòu)體指針的時(shí)候,就會(huì)發(fā)現(xiàn)C#上沒有類型可以對(duì)應(yīng)。這時(shí)怎么辦,第一反應(yīng)是C#也定義結(jié)構(gòu)體,然后當(dāng)成參數(shù)傳弟。然而,當(dāng)我們定義完一個(gè)結(jié)構(gòu)體后想傳遞參數(shù)進(jìn)去時(shí),會(huì)拋異常,或者是傳入了結(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)過查找資料,有文提到對(duì)于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é)果依然不理想,值要么出錯(cuò),要么沒有被改變。這究竟是什么原因?不斷的搜資料,終于看到了一篇,里面提到結(jié)構(gòu)體的傳遞,有的可以如上面所做,但有的卻不行,特別是當(dāng)參數(shù)在C++中是結(jié)構(gòu)體指針或者結(jié)構(gòu)體數(shù)組指針時(shí),在C#調(diào)用的地方也要用指針來對(duì)應(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); } }
要注意的是,這時(shí)接口已經(jīng)改成IntPtr了。通過以上方式,終于把結(jié)構(gòu)體數(shù)組給傳進(jìn)去了。不過,這里要注意一點(diǎn),不同的編譯器對(duì)結(jié)構(gòu)體的大小會(huì)不一定,比如上面的結(jié)構(gòu)體
在BCB中如果沒有字節(jié)對(duì)齊的話,有時(shí)會(huì)比一般的結(jié)構(gòu)體大小多出2兩個(gè)字節(jié)。因?yàn)锽CB默認(rèn)的是2字節(jié)排序,而VC是默認(rèn)1 個(gè)字節(jié)排序。要解決該問題,要么在BCB的結(jié)構(gòu)體中增加字節(jié)對(duì)齊,要么在C#中多開兩個(gè)字節(jié)(如果有多的話)。字節(jié)對(duì)齊代碼如下。
#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)存中還是一個(gè)一個(gè)字節(jié)存儲(chǔ)的,也就是說,最終是以一維的字節(jié)數(shù)組形式展現(xiàn)的,所以我們?nèi)绻_一個(gè)等大小的一維數(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
對(duì)于實(shí)在想不到要怎么傳數(shù)據(jù)的時(shí)候,可以考慮byte數(shù)組來傳(即便是整型也可以,只要是開辟4字節(jié)(在32位下)),只要開的長度對(duì)應(yīng)的上,在拿到數(shù)據(jù)后,要按類型規(guī)則轉(zhuǎn)換成所要的數(shù)據(jù),一般都能達(dá)到目的。
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
c# 代碼調(diào)試技巧和如何遠(yuǎn)程調(diào)試
這篇文章主要介紹了c# 代碼調(diào)試技巧和如何遠(yuǎn)程調(diào)試,幫助大家更好的理解和使用c#編程語言,感興趣的朋友可以了解下2020-11-11WPF利用DrawingContext實(shí)現(xiàn)繪制溫度計(jì)
這篇文章主要為大家詳細(xì)介紹了如何利用WPF和DrawingContext實(shí)現(xiàn)繪制溫度計(jì),文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)或工作有一定幫助,感興趣的小伙伴可以了解一下2022-09-09C# 泛型數(shù)組學(xué)習(xí)小結(jié)
C# 泛型數(shù)組學(xué)習(xí)中我們需要注意什么事項(xiàng)呢?C# 泛型數(shù)組的使用又是如何呢?那么本文就向你詳細(xì)介紹這方面的內(nèi)容2012-09-09