看書時(shí)發(fā)現(xiàn)書中沒(méi)有這方面的講解,于是自己動(dòng)手試驗(yàn)了一下,不知道這樣做是否“正點(diǎn)”
,歡迎討論。關(guān)于DLL最基本的知識(shí)就不提了,開(kāi)門見(jiàn)山地講吧!
現(xiàn)有動(dòng)態(tài)鏈接庫(kù)DLL_Sample.dll
DLL_Sample
.h:
#ifdef TEST_API
# define TEST_API _declspec(dllexport)
#else
# define TEST_API _declspec(dllimport)
#endif

TEST_API int fuc(int a);
TEST_API int fuc(int a, int b);
TEST_API int fuc(int a, int b, int c);
DLL_Sample.cpp:
#define TEST_API
#include "DLL_Sample.h"
TEST_API int fuc(int a)
{
return a;
}
TEST_API int fuc(int a, int b)
{
return a + b;
}
TEST_API int fuc(int a, int b, int c)
{
return a + b + c;
}
在動(dòng)態(tài)調(diào)用dll之前,需要查看一下dll導(dǎo)出的函數(shù)名稱。
查看編譯器的導(dǎo)出名稱,可以用VS工具目錄下的Dependency Walker,或者在控制臺(tái)下使用命令:dumpbin /exports DLL_Sample.dll
這里我用dumpbin命令得到下面的信息:
1 0 00011348 ?fuc@@YAHH@Z
2 1 00011352 ?fuc@@YAHHH@Z
3 2 000111DB ?fuc@@YAHHHH@Z
可以看到,重載函數(shù)各個(gè)版本的名稱是不同的,這是因?yàn)榫幾g器重新編碼了重載函數(shù)的名稱。
為了方便記憶和使用,我們需要指定重載函數(shù)的命名規(guī)則,由于導(dǎo)出函數(shù)名的唯一性,我們無(wú)法將重載函數(shù)指定成相同的名稱,所以我們采用fuc1、fuc2、fuc3來(lái)標(biāo)識(shí)fuc函數(shù)的不同版本。
我們用模塊定義文件(.def)來(lái)定義dll導(dǎo)出。
DLL_Sample.def:
LIBRARY DLL_Sample
EXPORTS
fuc1=?fuc@@YAHH@Z
fuc2=?fuc@@YAHHH@Z
fuc3=?fuc@@YAHHHH@Z
然后寫動(dòng)態(tài)調(diào)用的示例代碼(這里調(diào)用了第二個(gè)版本的fuc函數(shù)):

HINSTANCE hInst = LoadLibrary("Dll_Sample.dll");
typedef int (*MyProc)(int a, int b);
MyProc Fuc = (MyProc)GetProcAddress(hInst, "fuc2");
if (!Fuc)
{
MessageBox ("Fuc2 is null!");
return;
}
CString str;
str.Format ("a + b = %d", Fuc(2, 3) );
MessageBox(str);
FreeLibrary (hInst);


結(jié)果輸出“a + b = 5”