.NET 互操作
首先推薦一本書《精通.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 }
二、兩款 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 變量名 |
結構體封裝
View Code
附:
2. Dll Export Viewer 下載
3. Dll 函數查看器 2.0 下載

