C#調(diào)用C++DLL傳遞結(jié)構(gòu)體數(shù)組的終極解決方案
C#調(diào)用C++DLL傳遞結(jié)構(gòu)體數(shù)組的終極解決方案
在項目開發(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ù)進去時,會拋異常,或者是傳入了結(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)過這樣的改進后,運行結(jié)果依然不理想,值要么出錯,要么沒有被改變。這究竟是什么原因?不斷的搜資料,終于看到了一篇,里面提到結(jié)構(gòu)體的傳遞,有的可以如上面所做,但有的卻不行,特別是當(dāng)參數(shù)在C++中是結(jié)構(gòu)體指針或者結(jié)構(gòu)體數(shù)組指針時,在C#調(diào)用的地方也要用指針來對應(yīng),后面改進出如下代碼。
[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ù)組給傳進去了。不過,這里要注意一點,不同的編譯器對結(jié)構(gòu)體的大小會不一定,比如上面的結(jié)構(gòu)體
在BCB中如果沒有字節(jié)對齊的話,有時會比一般的結(jié)構(gòu)體大小多出2兩個字節(jié)。因為BCB默認(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,還有沒有其他的方式呢?
其實,不論C++中的是指針還是數(shù)組,最終在內(nèi)存中還是一個一個字節(jié)存儲的,也就是說,最終是以一維的字節(jié)數(shù)組形式展現(xiàn)的,所以我們?nèi)绻_一個等大小的一維數(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ù)據(jù)的時候,可以考慮byte數(shù)組來傳(即便是整型也可以,只要是開辟4字節(jié)(在32位下)),只要開的長度對應(yīng)的上,在拿到數(shù)據(jù)后,要按類型規(guī)則轉(zhuǎn)換成所要的數(shù)據(jù),一般都能達到目的。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
上一篇:C# salt+hash 加密
欄 目:C#教程
下一篇:C# 文件下載之?dāng)帱c續(xù)傳實現(xiàn)代碼
本文標(biāo)題:C#調(diào)用C++DLL傳遞結(jié)構(gòu)體數(shù)組的終極解決方案
本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/6007.html
您可能感興趣的文章
- 01-10C#調(diào)用dos窗口獲取相關(guān)信息的方法
- 01-10同步調(diào)用和異步調(diào)用WebService
- 01-10C#調(diào)用WebService實例開發(fā)
- 01-10C++調(diào)用C#的DLL程序?qū)崿F(xiàn)方法
- 01-10C# 調(diào)用 JavaWebservice服務(wù)遇到的問題匯總
- 01-10理解C#中參數(shù)的值和引用以及傳遞結(jié)構(gòu)和類引用的區(qū)別
- 01-10C#編程中使用ref和out關(guān)鍵字來傳遞數(shù)組對象的用法
- 01-10基于C#實現(xiàn)手機號碼歸屬地接口調(diào)用
- 01-10C#在WinForm中使用WebKit傳遞js對象實現(xiàn)與網(wǎng)頁交互的方法
- 01-10C#使用Process類調(diào)用外部exe程序


閱讀排行
本欄相關(guān)
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁無法打開的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實現(xiàn)txt定位指定行完整實例
- 01-10WinForm實現(xiàn)仿視頻播放器左下角滾動新
- 01-10C#停止線程的方法
- 01-10C#實現(xiàn)清空回收站的方法
- 01-10C#通過重寫Panel改變邊框顏色與寬度的
- 01-10C#實現(xiàn)讀取注冊表監(jiān)控當(dāng)前操作系統(tǒng)已
隨機閱讀
- 04-02jquery與jsp,用jquery
- 01-10delphi制作wav文件的方法
- 08-05織夢dedecms什么時候用欄目交叉功能?
- 01-10C#中split用法實例總結(jié)
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 01-10使用C語言求解撲克牌的順子及n個骰子
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-11ajax實現(xiàn)頁面的局部加載
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置


