一、創(chuàng)建Non-MFC DLL動態(tài)鏈接庫
1、打開File —> New —> Project選項,選擇Win32 Dynamic-Link Library —>sample project —>工程名:DllDemo
2、新建一個。h文件DllDemo.h
#ifdef DllDemo_EXPORTS #define DllAPI __declspec(dllexport) #else #define DllAPI __declspec(dllimport) extern "C" //原樣編譯 { DllAPI int __stdcall Max(int a,int b); //__stdcall使非C/C++語言內(nèi)能夠調(diào)用API } #endif |
3、在DllDemo.cpp文件中導入DllDemo.h文件,并實現(xiàn)Max(int,int)函數(shù)
#include "DllDemo.h" DllAPI int __stdcall Max(int a,int b) { if(a==b) return NULL; else if(a>b) return a; else return b; } |
4、編譯程序生成動態(tài)連接庫
二、用。def文件創(chuàng)建動態(tài)連接庫DllDemo.dll
1、刪除DllDemo工程中的DllDemo.h文件。
2、在DllDemo.cpp文件頭,刪除 #include DllDemo.h語句。
3、向該工程中加入一個文本文件,命名為DllDemo.def并寫入如下語句:
LIBRARY MyDll
EXPORTS
Max@1
4、編譯程序生成動態(tài)連接庫。
動態(tài)鏈接的調(diào)用步驟:
一、隱式調(diào)用
1、建立DllCnslTest工程
2、將文件DllDemo.dll、DllDemo.lib拷貝到DllCnslTest工程所在的目錄
3、在DllCnslTest.h中添加如下語句:
#define DllAPI __declspec(dllimport) #pragma comment(lib,"DllDemo.lib") //在編輯器link時,鏈接到DllDemo.lib文件 extern "C" { DllAPI int __stdcall Max(int a,int b); } |
4、在DllCnslTest.cpp文件中添加如下語句:
#include "DllCnslTest.h"http://或者 #include "DllDemo.h" void main() { int value; value = Max(2,9); printf("The Max value is %d\n",value); } |
5、編譯并生成應(yīng)用程序DllCnslTest.exe
二、顯式調(diào)用
1、建立DllWinTest工程。
2、將文件DllDemo.dll拷貝到DllWinTest工程所在的目錄或Windows系統(tǒng)目錄下。
3、用vc/bin下的Dumpbin.exe的小程序,查看DLL文件(DllDemo.dll)中的函數(shù)結(jié)構(gòu)。
4、使用類型定義關(guān)鍵字typedef,定義指向和DLL中相同的函數(shù)原型指針。
例:
typedef int(*lpMax)(int a,int b); //此語句可以放在.h文件中 |
5、通過LoadLibray()將DLL加載到當前的應(yīng)用程序中并返回當前DLL文件的句柄。
例:
HINSTANCE hDll; //聲明一個Dll實例文件句柄 hDll = LoadLibrary("DllDemo.dll");//導入DllDemo.dll動態(tài)連接庫 |
例:
lpMax Max; Max = (lpMax)GetProcAddress(hDLL,"Max"); int value; value = Max(2,9); printf("The Max value is %d",value); |
FreeLibrary(hDll); |
8、編譯并生成應(yīng)用程序DllWinTest.exe
注:顯式鏈接應(yīng)用程序編譯時不需要使用相應(yīng)的Lib文件。