標籤:style blog http io ar color os sp strong
首先推薦一本書《精通.NET 互操作》 ,這本書是目前中文資料裡講 互操作最詳盡的書了。
做系統整合項目的同學應該都和裝置打過交道(如視頻裝置:海康、大華等),在大多數情況下這些裝置廠商會給系統整合廠商開發協議(dll 類庫、 函數定義的標頭檔、測試程式、調用流程),這些協議的dll 大都用C++開發的,那麼我們用C#整合,就得用 P/Invoke 技術(.NET 互操作的一種)
一、P/Invoke 簡單例子
P/Invoke 說白了,就是你調用協議dll 的函數,傳入正確的參數(注意C++與C#的資料類型轉換)
例子:
1 using System.Runtime.InteropServices; 2 3 class App 4 { 5 [DllImport("msvcrt.dll")] 6 static extern int puts(string msg); 7 8 [DllImport("msvcrt.dll")] 9 static extern int _flushall();10 11 static void Main()12 {13 puts("Hello World");14 _flushall();15 CreateMsgWindow();16 }17 18 19 [DllImport("user32.dll",EntryPoint="MessageBox")]20 static extern int MessageBox(int hwnd,string lpText,string lpCaption,int wType);21 22 static void CreateMsgWindow()23 {24 MessageBox(0,"Hello world!","Welcome",0);25 }26 }View Code
二、兩款 dll 函數查看工具
1. Dll Export Viewer
2. Dll 函數查看器 2.0
三、C#與C++常見類型對比
| C++ 類型 |
C# 類型 |
| HANDLE (void *)括弧內是等價類別型 |
IntPtr |
| Byte(unsigned char) |
byte |
| SHORT(short) |
short |
| WORD(unsigned short) |
short |
| INT(int) |
int |
| int* |
ref int |
| UINT(unsigned int) |
int |
| LONG(long) |
int |
| ULONG(unsigned long) |
uint |
| DWORD(unsigned long) |
uint |
| BOOL(long) |
bool |
| PCAHR(char *) |
string |
| char[] |
string |
| PBYTE(byte *) |
byte[] |
| 結構體 |
publlic struct 結構體{} |
| char **變數名 |
ref string 變數名 |
結構體封裝
1 // 協議標頭檔中的結構體 2 typedef struct 3 { 4 char sLibName[ 256 ]; 5 char sPathToLibrary[ 256 ]; 6 INT32 iEntries; 7 INT32 iUsed; 8 UINT16 iSort; 9 UINT16 iVersion; 10 BOOLEAN fContainsSubDirectories; 11 INT32 iReserved; 12 } LIBHEADER; 13 14 // C#協議包裹類中的對應結構15 [StructLayout(LayoutKind.Sequential)] 16 public struct LIBHEADER 17 { 18 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)] 19 public char[] sLibName; 20 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)] 21 public char[] sPathToLibrary; 22 public int iEntries; 23 public int iUsed; 24 public ushort iSort; 25 public ushort iVersion; 26 public bool fContainsSubDirectories; 27 public int iReserved; 28 } View Code
附:
1. 精通.NET 互操作 pdf 和 iso 下載
2. Dll Export Viewer 下載
3. Dll 函數查看器 2.0 下載
.NET 互操作