1. 程式人生 > >[C#/C++]C#呼叫非託管DLL的APIs

[C#/C++]C#呼叫非託管DLL的APIs

上網baidu一下或google一下這個東東就有很多人在問這個問題,最近我也用到了這個,所以就留下來以備往後需要是可以查詢。我想通過這個來作為C#呼叫windows APIs的出發點,在以後的隨筆當中介紹一下我現階段用到的一些APIs或非託管類庫。在呼叫非託管DLL的APIs前,我們應該好好掌握一下DllImportAttribute,MSDN給出的定義為:可將該屬性應用於方法。DllImportAttribute 屬性提供對從非託管 DLL 匯出的函式進行呼叫所必需的資訊。作為最低要求,必須提供包含入口點的 DLL 的名稱。

[DllImport("KERNEL32.DLL", EntryPoint="MoveFileW",     SetLastError=true,
CharSet=CharSet.Unicode, ExactSpelling=true,
CallingConvention=CallingConvention.StdCall)]
public static extern bool MoveFile(String src, String dst);


     從上面的例子中我們可以看出,從Kernel32.dll中引入這個API,其中EntryPoint一看就知道是入口點,也就是DLL中的函式名稱。其實只要用過VC++的人都知道,Windows APIs中都提供兩個版本,一個是W,一個是A也就是Ansi和Unicode之分,現在一般都採用W,Unicode程式設計,但是.Net和win32互動的時候,預設是使用CharSet.Ansi來傳送。在 DllImportAttribute.ExactSpelling 欄位為 true 時(它是 Visual Basic .NET 中的預設值),平臺呼叫將只搜尋您指定的名稱。例如,如果指定 MessageBox,則平臺呼叫將搜尋 MessageBox,如果它找不到完全相同的拼寫則失敗。當 ExactSpelling 欄位為 false(它是 C++ 託管擴充套件和 C# 中的預設值),平臺呼叫將首先搜尋未處理的別名 (MessageBox),如果沒有找到未處理的別名,則將搜尋已處理的名稱 (MessageBoxA)。

    由於很多引數和C#中有所區別,下面讓我們看看引數是怎麼個情況:

    extern “C” __declspec(dllexport)  int WINAPI sumAB(int a,int b)這個和C#中一樣是值型別,a及b的變化不會對C#中的引數造成影響。通過DllImport表示為:

1 [DllImport(“CppDll.dll")]
2 //返回個int 型別3 public static extern int sumAB (int a1,int b1); 
    下面的是引用型別:也就是說a和b的變化直接影響到a1和b1的值。 public static extern int sum (ref int a1,ref int b1);
//DLL中申明extern “C” __declspec(dllexport)  int WINAPI sum(int *a,int *b) 

同理我們可以得到一下幾種傳值方法:第一種引數的改變不影響C#中引數的變化,需要傳入char*型別。

[DllImport(“CppDll.dll")]
//傳入值public static extern int together (string  astr,string bstr);
//DLL中申明extern “C” __declspec(dllexport)  int WINAPI together(char * stra,char * strb) 
    當我們需要從引數中傳出char*型別是,那我們就要用到StringBuilder了。

1 // 傳出值2 public static extern int getParameter (StringBuilder sb1, StringBuilder sb2);
3 //DLL中申明4 extern “C” __declspec(dllexport)  int WINAPI getParameter(char * stra,char * strb) 
  接著我們先來看看結構的封送,這裡我們要看看StructLayoutAttribute這個標籤,通過它可以定義自己的格式化型別,在託管程式碼中,格式化型別是一個用StructLayoutAttribute說明的結構或類成員,通過它能夠保證其內部成員預期的佈局資訊,他的成員說明如下:

  LayoutKind.Automatic 為了提高效率允許執行態對型別成員重新排序。注意:永遠不要使用這個選項來呼叫非託管的動態連結庫函式。

     LayoutKind.Explicit 對每個域按照FieldOffset屬性對型別成員排序

     LayoutKind.Sequential 對出現在託管型別定義地方的非託管記憶體中的型別成員進行排序。
 我們可以通過GetSystemInfo來獲取系統的資訊,程式碼如下:

 1 using System.Runtime.InteropServices;
 2 [StructLayout(LayoutKind.Sequential)]
 3     public struct SYSTEM_INFO {
 4     public uint dwOemId;
 5     public uint dwPageSize;
 6     public uint lpMinimumApplicationAddress;
 7     public uint lpMaximumApplicationAddress;
 8     public uint dwActiveProcessorMask;
 9     public uint dwNumberOfProcessors;
10     public uint dwProcessorType;
11     public uint dwAllocationGranularity;
12     public uint dwProcessorLevel;
13     public uint dwProcessorRevision;
14 }
15 //呼叫
16 [DllImport("kernel32")]
17 static extern void GetSystemInfo(ref SYSTEM_INFO pSI);
18 SYSTEM_INFO pSI = new SYSTEM_INFO();
19 GetSystemInfo(ref pSI);

 當我們遇到函式指標引數是我們就需要考慮是否要用到回撥函式,例如列舉所有視窗。

BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARMAM IParam);

   我們可以通過建立一個代理,它帶有兩個引數hwnd和lparam,第一個引數是一個視窗控制代碼,第二個引數由應用程式定義,兩個引數均為整形。當這個回撥函式返回一個非零值時,標示執行成功,零則暗示失敗,這個例子總是返回True值,以便持續列舉。最後建立以代理物件(delegate),並把它作為一個引數傳遞給EnumWindows 函式,平臺會自動地 把代理物件轉化成函式能夠識別的回撥格式。

 1 using System;
 2 using System.Runtime.InteropServices;
 3 public delegate bool CallBack(int hwnd, int lParam);
 4 public class EnumReportApp {
 5 [DllImport("user32")]
 6 public static extern int EnumWindows(CallBack x, int y);
 7 public static void Main()
 8 {
 9 CallBack myCallBack = new CallBack(EnumReportApp.Report);
10 EnumWindows(myCallBack, 0);
11 }
12 public static bool Report(int hwnd, int lParam) {
13 Console.Write("視窗控制代碼為");
14 Console.WriteLine(hwnd);
15 return true;
16 }
17 }
  OK,如果熟悉了以上方方面面,基本上也能夠呼叫APIs了別忘了P/Invoke能夠幫上很大的忙,我們可以去wiki網站查詢我們所要的API:http://pinvoke.net。還需要說明的是很多例子等都來自MSDN和網上檢索得到的!!!