(本文來自網際網路) C#與C++資料轉換問題 https://www.cnblogs.com/82767136/articles/2517457.html
(本文來自網際網路)
C#與C++資料轉換問題
https://www.cnblogs.com/82767136/articles/2517457.html
在合作開發時,C#時常需要呼叫C++DLL,當傳遞引數時時常遇到問題,尤其是傳遞和返回字串是,現總結一下,分享給大家:
VC++中主要字串型別為:LPSTR,LPCSTR, LPCTSTR, string, CString, LPCWSTR, LPWSTR等
但轉為C#型別卻不完全相同。
主要有如下幾種轉換:
將string轉為IntPtr:IntPtr System.Runtime.InteropServices.Marshal.StringToCoTaskMemAuto(string)
將IntPtr轉為string:string System.Runtime.InteropServices.MarshalPtrToStringAuto(IntPtr)
型別對照:
BSTR --------- StringBuilder
LPCTSTR --------- StringBuilder
LPCWSTR --------- IntPtr
handle---------IntPtr
hwnd-----------IntPtr
char *----------string
int * -----------ref int
int &-----------ref int
void *----------IntPtr
unsigned char *-----ref byte
Struct需要在C#裡重新定義一個Struct
CallBack回撥函式需要封裝在一個委託裡,delegate static extern int FunCallBack(string str);
注意在每個函式的前面加上public static extern +返回的資料型別,如果不加public ,函式預設為私有函式,呼叫就會出錯。
在C#呼叫C++ DLL封裝庫時會出現兩個問題:
1. 資料型別轉換問題
2. 指標或地址引數傳送問題
首先是資料型別轉換問題。因為C#是.NET語言,利用的是.NET的基本資料型別,所以實際上是將C++的資料型別與.NET的基本資料型別進行對應。 例如C++的原有函式是:
int __stdcall FunctionName(unsigned char param1, unsigned short param2)
其中的引數資料型別在C#中,必須轉為對應的資料型別。如:
[DllImport(“ COM DLL path/file ”)]
extern static int FunctionName(byte param1, ushort param2)
因為呼叫的是__stdcall函式,所以使用了P/Invoke的呼叫方法。其中的方法FunctionName必須宣告為靜態外部函式,即加上extern static宣告頭。我們可以看到,在呼叫的過程中,unsigned char變為了byte,unsigned short變為了ushort。變換後,引數的資料型別不變,只是宣告方式必須改為.NET語言的規範。
我們可以通過下表來進行這種轉換:
Win32 Types
CLR Type
char, INT8, SBYTE, CHAR
System.SByte
short, short int, INT16, SHORT
System.Int16
int, long, long int, INT32, LONG32, BOOL , INT
System.Int32
__int64, INT64, LONGLONG
System.Int64
unsigned char, UINT8, UCHAR , BYTE
System.Byte
unsigned short, UINT16, USHORT, WORD, ATOM, WCHAR , __wchar_t
System.UInt16
unsigned, unsigned int, UINT32, ULONG32, DWORD32, ULONG, DWORD, UINT
System.UInt32
unsigned __int64, UINT64, DWORDLONG, ULONGLONG
System.UInt64
float, FLOAT
System.Single
double, long double, DOUBLE
System.Double
之後再將CLR的資料型別表示方式轉換為C#的表示方式。這樣一來,函式的引數型別問題就可以解決了。
現在,我們再來考慮下一個問題,如果要呼叫的函式引數是指標或是地址變數,怎麼辦?
對於這種情況可以使用C#提供的非安全程式碼來進行解決,但是,畢竟是非託管程式碼,垃圾資源處理不好的話對應用程式是很不利的。所以還是使用C#提供的ref以及out修飾字比較好。
同上面一樣,我們也舉一個例子:
int __stdcall FunctionName(unsigned char ¶m1, unsigned char *param2)
在C#中對其進行呼叫的方法是:
dllImport(“ file ”)]
extern static int FunctionName(ref byte param1, ref byte param2)
看到這,可能有人會問,&是取地址,*是傳送指標,為何都只用ref就可以了呢?一種可能的解釋是ref是一個具有過載特性的修飾符,會自動識別是取地址還是傳送指標。
在實際的情況中,我們利用引數傳遞地址更多還是用在傳送陣列首地址上。
如:byte[] param1 = new param1(6);
在這裡我們聲明瞭一個數組,現在要將其的首地址傳送過去,只要將param1陣列的第一個元素用ref修飾。具體如下:
[DllImport(“ file ”)]
extern static int FunctionName(ref byte param1[1], ref byte param2)
C# 中呼叫DLL
為了能用上原來的C++程式碼,只好研究下從C# 中呼叫DLL
首先必須要有一個宣告,使用的是DllImport關鍵字:
包含DllImport所在的名字空間
複製程式碼
using System.Runtime.InteropServices;
public class XXXX{
[DllImport(“MyDLL.dll")]
public static extern int mySum (int a,int b);
}
[DllImport(“MyDLL.dll")]
public static extern int mySum (int a,int b);
複製程式碼
程式碼中DllImport關鍵字作用是告訴編譯器入口點在哪裡,並將打包函式捆綁在這個類中
在呼叫的時候
在類中的時候 直接 mySum(a,b);就可以了
在其他類中呼叫: XXXX. mySum(a,b);
EntryPoint: 指定要呼叫的 DLL 入口點。預設入口點名稱是託管方法的名稱 。
CharSet: 控制名稱重整和封送 String 引數的方式 (預設是UNICODE)
CallingConvention指示入口點的函式呼叫約定(預設WINAPI)(上次報告講過的)
SetLastError 指示被呼叫方在從屬性化方法返回之前是否呼叫 SetLastError Win32 API 函式 (C#中預設false )
int 型別
複製程式碼
[DllImport(“MyDLL.dll")]
//返回個int 型別
public static extern int mySum (int a1,int b1);
//DLL中申明
extern “C” __declspec(dllexport) int WINAPI mySum(int a2,int b2)
{
//a2 b2不能改變a1 b1
//a2=…
//b2=…
return a+b;
}
//引數傳遞int 型別
public static extern int mySum (ref int a1,ref int b1);
//DLL中申明
extern “C” __declspec(dllexport) int WINAPI mySum(int *a2,int *b2)
{
//可以改變 a1, b1
*a2=…
*b2=…
return a+b;
}
DLL 需傳入char *型別
[DllImport(“MyDLL.dll")]
//傳入值
public static extern int mySum (string astr1,string bstr1);
//DLL中申明
extern “C” __declspec(dllexport) int WINAPI mySum(char * astr2,char * bstr2)
{
//改變astr2 bstr 2 ,astr1 bstr1不會被改變
return a+b;
}
DLL 需傳出char *型別
[DllImport(“MyDLL.dll")]
// 傳出值
public static extern int mySum (StringBuilder abuf, StringBuilder bbuf );
//DLL中申明
extern “C” __declspec(dllexport) int WINAPI mySum(char * astr,char * bstr)
{
//傳出char * 改變astr bstr -->abuf, bbuf可以被改變
return a+b;
}
複製程式碼
DLL 回撥函式
BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam)
複製程式碼
using System;
using System.Runtime.InteropServices;
public delegate bool CallBack(int hwnd, int lParam); //定義委託函式型別
public class EnumReportApp
{
[DllImport(“user32”)]
public static extern int EnumWindows(CallBack x, int y);
public static void Main() {
CallBack myCallBack = new CallBack(EnumReportApp.Report); EnumWindows(myCallBack, 0);
}
public static bool Report(int hwnd, int lParam)
{
Console.Write("Window handle is ");
Console.WriteLine(hwnd); return true;
}
}
複製程式碼
DLL 傳遞結構
BOOL PtInRect(const RECT *lprc, POINT pt);
複製程式碼
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public struct Point {
public int x;
public int y;
}
[StructLayout(LayoutKind.Explicit)]
public struct Rect
{
[FieldOffset(0)] public int left;
[FieldOffset(4)] public int top;
[FieldOffset(8)] public int right;
[FieldOffset(12)] public int bottom;
}
Class XXXX {
[DllImport(“User32.dll”)]
public static extern bool PtInRect(ref Rect r, Point p);
}
複製程式碼
DLL 回撥函式,傳遞結構 想看的msdn裡面都有專題介紹,看的我都是暈暈的:)
其他參考請搜尋:
在C#程式設計中使用Win32類庫
C#中呼叫C++託管Dll
如何在C#中載入自己編寫的動態連結庫
相關文章:Creating a P/Invoke Library
能用上DLL以後感覺還是很好的,原來的C++程式碼只要修改編譯通過就可以了,
高興沒多久,發現.net2005居然可以用VB,VC開發智慧裝置專案,可以建立MFC智慧裝置專案
暈暈,難道可以直接用MFC來開發smartphone的程式了,趕緊看看,,,
Visual C++ 使用 __declspec(dllexport) 從 DLL 匯出 (到C#)
由於各種的原因, 如何把unmanaged 的 c++ DLL 轉換成 managed C# 是一個問題。
方法有3個.
Ø 使用.def檔案
Ø 可以不用.def檔案, 使用__declspec(dllexport)關鍵字, 特別是針對Visual C++編譯器的時候
Ø 直接用MC++寫
什麼時候用.def檔案?
.def的意思是module-definition, 這個純文字的檔案定義了模組的資訊。 對於編譯器來說, 一個方法在編譯之後的DLL檔案裡, 存在的形式名字可能不是作者當時起的那個,例如好好的函式名字function() 變成了[email protected]@YAXXZ; 可以用undname檢視這個被編譯器修飾掉的名字, 原型是"void __cdecl function2(void)". 大概使用的時候就會遇到類似”連結錯誤,未決的外部符號…” 的錯誤.
.def檔案主要的作用, 就是”標註” 出這個函式原來的樣子, 這樣編譯器在編譯的時候, 規則上就會以C編譯器的規則來處理, 修飾被去掉了, 另外同時可以把匯出函式的序號值手動的改高一點; 還有一個優點(也是缺點) 就是可以用NONAME來修飾函式, 這樣匯出函式的序號值就變成了1~N, 即第N個函式. 所以呼叫GetProcAddress() 的時候, 可以直接用定義的序號值, 而不用寫函式的名字(但是名字就完全不可用了), 更好的是, 匯出函式的這個DLL會變得比較小, 當然, MSDN強調了一點: 僅你可以並有權更改這個.def檔案內容的時候, 你才可以用這個辦法.
那麼, 什麼時候考慮用.def檔案呢? 因為編譯器不同, 而產生的修飾名不同的話, 這個檔案就是必須的.
注意如果檔案沒有匯出函式的話, 這個檔案可能降低執行效率。
.def檔案的格式
LIBRARY FileNameWithoutExtension
EXPORTS
Function1 @1
Function3 @2
Function2 @3 NONAME
啟用 Enable it: Property pages-> Configuration Properties->C/C++ -> Linker -> input -> Module Definition File
那不用.def呢? __declspec(dllexport)的作用
這個東西, 可以給函式用, 也可以給類用. 宣告大概這樣子:
view source
< id=“highlighter_930381_clipboard” title=“copy to clipboard” classid=“clsid:d27cdb6e-ae6d-11cf-96b8-444553540000” width=“16” height=“16” codebase=“http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0” type=“application/x-shockwave-flash”>
print?
1 __declspec(dllexport) int __stdcall GetMid(vector ve);
2 class __declspec(dllexport) TestClass{
3 public :
4 TestClass();
5 }
這牽扯到了一個東西就是__stdcall和__cdecl (還有__fastcall, 不過很少用), 其中__cdecl一般是C或者C++的預設呼叫規範, 但是最大的一個區別就是__stdcall在返回前自身清除堆疊, 而__cdecl是呼叫方來做這個事情(可參考COM中的某些機制), 另一個區別就是__stdcall對於可變引數的函式, 玩不轉.
反正今時今日, 大家都在用__stdcall, 所以這麼寫也沒什麼問題, 但不是沒有. VB裡呼叫標記著__cdecl的方法, 可能會得到一個異常Bad DLL Calling Convention. 解決方法也很簡單:
原來的函式
view source
< id=“highlighter_718220_clipboard” title=“copy to clipboard” classid=“clsid:d27cdb6e-ae6d-11cf-96b8-444553540000” width=“16” height=“16” codebase=“http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0” type=“application/x-shockwave-flash”>
print?
1 long _cdecl PassStr(LPSTR pStr)
2 { return 1; }
新的函式
view source
< id=“highlighter_515163_clipboard” title=“copy to clipboard” classid=“clsid:d27cdb6e-ae6d-11cf-96b8-444553540000” width=“16” height=“16” codebase=“http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0” type=“application/x-shockwave-flash”>
print?
1 long _stdcall PassStrStdCall(LPSTR pStr)
2 { return PassStr(pStr); }
問題是, 如果這個函式原型, 引數是可變的, 那又怎麼弄呢?
呼叫的時候, C#都是這麼寫的:
view source
< id=“highlighter_120154_clipboard” title=“copy to clipboard” classid=“clsid:d27cdb6e-ae6d-11cf-96b8-444553540000” width=“16” height=“16” codebase=“http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0” type=“application/x-shockwave-flash”>
print?
1 [DllImport("", EntryPoint = @" [email protected]@YAXXZ", CharSet = CharSet.Auto)]
2 private static extern void GetMid(…);
這個入口點名字還真彆扭, 看來去掉這個修飾還是蠻需要的, 除了用.def檔案, 另一個辦法就是用 extern “C”.
Extern “C”
一句話總結:這個東西可以去掉修飾名。在不用.def檔案的前提下, 這個可以保證你的函式function() 還是這個名字.
但是,這個東西對類不太起作用!
這個東西是這麼用的: 放到函式宣告的最前面。 就類似這樣 extern “C” void __declspec(dllexport) function(void);
對於類, 一般的做法是, 把它的內部方法(特別是例項方法,或變數),wrap出一個方法來。 見下面的例項.
還要做什麼?
當一個DLL被初始化的時候, 它需要一個入口點, 一般對於非MFC DLL來說, 這樣寫就行了:
view source
< id=“highlighter_702691_clipboard” title=“copy to clipboard” classid=“clsid:d27cdb6e-ae6d-11cf-96b8-444553540000” width=“16” height=“16” codebase=“http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0” type=“application/x-shockwave-flash”>
print?
01 BOOL APIENTRY DllMain(HANDLE hModule,
02 DWORD ul_reason_for_call,
03 LPVOID lpReserved
04 )
05 {
06 switch( ul_reason_for_call )
07 {
08 case DLL_PROCESS_ATTACH:
09 case DLL_THREAD_ATTACH:
10 case DLL_THREAD_DETACH:
11 case DLL_PROCESS_DETACH:
12 break;
13 }
14 return TRUE;
15 }
要注意的是這個入口點的名字必須是DllMain, 如果不是需要修改linker的/entry 選項. 否則對於C的話可能會初始化失敗.
開始用匯出函式 PInvoke
為了好看一點, 先約定一下:
view source
< id=“highlighter_95255_clipboard” title=“copy to clipboard” classid=“clsid:d27cdb6e-ae6d-11cf-96b8-444553540000” width=“16” height=“16” codebase=“http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0” type=“application/x-shockwave-flash”>
print?
1 #define EXT_C extern “C”
2 #define DLLEXPORT __declspec(dllexport)
3 #define EXT_C_DLLEXPORT EXT_C DLLEXPORT
4 #define CALLBACK __stdcall
5 #define WINAPI __stdcall
6 #define APIENTRY WINAPI
- 普通的函式
view source
< id=“highlighter_171056_clipboard” title=“copy to clipboard” classid=“clsid:d27cdb6e-ae6d-11cf-96b8-444553540000” width=“16” height=“16” codebase=“http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0” type=“application/x-shockwave-flash”>
print?
1 EXT_C_DLLEXPORT void WINAPI Function();
2
3 [DllImport(“filename.dll”, EntryPoint = " Function")]
4 private static extern void Func();
- ref或者out
view source
< id=“highlighter_733498_clipboard” title=“copy to clipboard” classid=“clsid:d27cdb6e-ae6d-11cf-96b8-444553540000” width=“16” height=“16” codebase=“http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0” type=“application/x-shockwave-flash”>
print?
1 EXT_C_DLLEXPORT void WINAPI Function(Type** ty);
2
3 [DllImport(“filename.dll”, EntryPoint = " Function")]
4 private static extern void Func(out Type ty);
- 指標函式和委託
view source
< id=“highlighter_987259_clipboard” title=“copy to clipboard” classid=“clsid:d27cdb6e-ae6d-11cf-96b8-444553540000” width=“16” height=“16” codebase=“http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0” type=“application/x-shockwave-flash”>
print?
1 Typedef void (CALLBACK *pFunc)(int);
2 EXT_C_DLLEXPORT void WINAPI Compare(int a, int b, pFunc p);
3 private delegate int CompareCallback(int a, int b);
4 [DllImport(“filename.dll”,EntryPoint=”Compare”)]
5 private static extern int Compare(int a, int b, CompareCallback call);
- 類的處理. 其實不是說不可以把類標記為 DLLEXPORT, 如果可以的話, 當然是wrap比較好
C++裡的原型
view source
< id=“highlighter_909839_clipboard” title=“copy to clipboard” classid=“clsid:d27cdb6e-ae6d-11cf-96b8-444553540000” width=“16” height=“16” codebase=“http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0” type=“application/x-shockwave-flash”>
print?
1 class DLLEXPORT Test
2 {
3 public :
4 Test();
5 ~Test();
6 BOOL function(int par)
7 };
類被export, 函式呼叫時候注意用CallingConvention.ThisCall.
view source
< id=“highlighter_447728_clipboard” title=“copy to clipboard” classid=“clsid:d27cdb6e-ae6d-11cf-96b8-444553540000” width=“16” height=“16” codebase=“http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0” type=“application/x-shockwave-flash”>
print?
1 [DllImport(“filename.dll”, EntryPoint = @"[email protected]@[email protected]@@Z", CallingConvention = CallingConvention.ThisCall)]
2 private static extern int TestFunc(IntPtr hwnd, int par);
採用了”迂迴”策略, C++裡先這樣定義,同理, 新增建構函式等, 函式就變成了這個樣子:
view source
< id=“highlighter_371353_clipboard” title=“copy to clipboard” classid=“clsid:d27cdb6e-ae6d-11cf-96b8-444553540000” width=“16” height=“16” codebase=“http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0” type=“application/x-shockwave-flash”>
print?
01 EXT_C_DLLEXPORT BOOL WINAPI function_wrap(Test* t, int par)
02 {
03 return t->function(par);
04 }
05 EXT_C_DLLEXPORT Test* Test_ctor()
06 {
07 Test* t = new Test();
08 return t;
09 }
10 EXT_C_DLLEXPORT void Test_dector(Test* t)
11 {
12 if(NULL == t)
13 {
14 delete t;
15 t = NULL;
16 }
17 }
在C#裡這樣寫, 那麼就和平時用沒什麼區別了.
view source
< id=“highlighter_413990_clipboard” title=“copy to clipboard” classid=“clsid:d27cdb6e-ae6d-11cf-96b8-444553540000” width=“16” height=“16” codebase=“http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0” type=“application/x-shockwave-flash”>
print?
01 public class Test : IDisposable
02 {
03 private IntPtr instance;
04 public Test()
05 {
06 instance = CreateInstance();
07 }
08
09 ~Test()
10 {
11 Dispose(false);
12 }
13
14 #region pinvoke
15 [DllImport(“filename.dll”, EntryPoint = @“Test_ctor”)]
16 private static extern IntPtr CreateInstance();
17 [DllImport(“filename.dll”, EntryPoint = @“Test_dector”)]
18 private static extern void DestroyInstance(IntPtr hwnd);
19 [return: MarshalAs(UnmanagedType.Bool)]
20 [DllImport(“filename.dll”, EntryPoint = @“function_wrap”)]
21 private static extern bool function_wrap(int par);
22 #endregion
23
24 #region IDisposable Members
25
26 public void Dispose()
27 {
28 Dispose(true);
29 }
30
31 private void Dispose(bool bDisposing)
32 {
33 if (instance != IntPtr.Zero)
34 {
35 DestroyInstance(instance);
36 }
37
38 if (bDisposing)
39 {
40 GC.SuppressFinalize(this);
41 }
42 }
43
44 #endregion
45 }
- Struct操作.
view source
< id=“highlighter_777150_clipboard” title=“copy to clipboard” classid=“clsid:d27cdb6e-ae6d-11cf-96b8-444553540000” width=“16” height=“16” codebase=“http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0” type=“application/x-shockwave-flash”>
print?
1 typedef struct Object_HANDLE {
2 unsigned long dbch_size;
3 HANDLE dbch_handle;
4 GUID dbch_eventguid;
5 BOOL res_flag;
6 } Object_Native_HANDLE ;
首先在C#裡嚴格定義這個,LayoutKind.Sequential 用來保證記憶體分配的正常。
view source
< id=“highlighter_876084_clipboard” title=“copy to clipboard” classid=“clsid:d27cdb6e-ae6d-11cf-96b8-444553540000” width=“16” height=“16” codebase=“http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0” type=“application/x-shockwave-flash”>
print?
1 [StructLayout(LayoutKind.Sequential)]
2 public struct Object_Native_HANDLE
3 {
4 public ulong dbch_size;
5 public IntPtr dbch_handle;
6 public Guid dbch_eventGuid;
7 public bool res_flag;
8 }
Marshal的使用如下:
view source
< id=“highlighter_487393_clipboard” title=“copy to clipboard” classid=“clsid:d27cdb6e-ae6d-11cf-96b8-444553540000” width=“16” height=“16” codebase=“http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0” type=“application/x-shockwave-flash”>
print?
1 Object_Native_HANDLE obj = new Object_Native_HANDLE(); //初始化
2 int amountToAllocate = Marshal.SizeOf(obj);//獲取大小
3 IntPtr objPtr = Marshal.AllocHGlobal(amountToAllocate); //分配並獲取空的空間地址
4 Marshal.StructureToPtr(obj, objPtr, false); // 值寫入分配的空間
5 //操作…
6 Marshal.FreeHGlobal(objPtr);//釋放空間
最後提一句, unmaged code中的錯誤, 到managed 以後, 極大可能是捕捉不到的。 所以錯誤需要分別處理。
花了不少時間, MC++平時用的不多, 不寫了。