[DLL][Win32] 創建一簡易動態連結函式庫-DLL

  • 8256
  • 0

[DLL][Win32] 創建一簡易動態連結函式庫-DLL
簡易條列幾項製作dll需要使用到的函式...

從之前就很想寫個dll來玩一下,只是老師教了概念,實作我真是不太懂,完全不知道從何下手...此時就從網路下手...查吧...查吧...不是罪...

 

1. 從Vitual Studio去[新增]一個專案,選擇[Win32]底下隨意一個專案樣本類型,並如下圖選擇[DLL]選項。

由於我們並沒特地選擇空的專案,所以VS會幫忙添加一些必要的檔頭及DLL進入點(Entry Point),DllMain:

DLL-1

 

2. 可以看到他有新增一檔為dllmain.cpp,如下圖的解釋;他是定義DLL應用程式的進入點。

MSDN dllmain entry point:

An optional entry point into a dynamic-link library (DLL). When the system starts or terminates a process or thread, it calls the entry-point function for each loaded DLL using the first thread of the process. The system also calls the entry-point function for a DLL when it is loaded or unloaded using the LoadLibrary and FreeLibraryfunctions.

 

當程式開啟或卸載dll的程序或執行緒時,就會呼叫到這個DLL應用程式進入點,但這個進入點並不是必要的。

image

在dllmain可以對變數做初始化或再定義的動作。

 

如何導入dll內的函式?

- 在dll中定義作為介面的函式,需要前頭多寫入關鍵字__declspec(dllexport)這個函式才可以使用且對應到呼叫dll的程式內。若dll中的函式沒有多定義__declspec(dllexport),就表示這個函是只能在dll內部使用,外部呼叫dll並不能使用這個函式喔!

image

 

- 若沒使用上述關鍵字的方法,可添加一個或多個模組定義文件(.def)檔案來描述dll。

EX:

LIBRARY   FILENAME
EXPORTS
   add_func

 

在要呼叫dll的程式中要如何載入/ 卸載DL呢?

 

1. 載入dll使用LoadLibrary("xxx.dll"),xxx.dll是我們要載入的dll名稱+副檔名。

image

 

2. 當load成功之後可使用GetProcAddress並強制轉型去取得library中的函式位址。

image

 

3. 若所要使用的函式位址非為0,表示成功取得位址。此時即可開始利用那個函式。使用完畢後切記要將資源釋放,是使用FreeLibrary的函式。

image

 

在主要程式中如何定義dll中的函式?

可利用typedef 方法來定義函式。

EX:

typedef int (*lpAdd)(int, int);

 

Note: 使用VS2008

 

參考:http://msdn.microsoft.com/en-us/library/ms682599(v=VS.85).aspx

 

沒試過,別說你不行!該努力就去努力,別過了再說後悔。

〈請多指教,新手上路〉