1.創(chuàng)建dll工程
以創(chuàng)建win32 dll程序?yàn)槔话阌袃煞N方式:
一種是建立lib鏈接方式的dll:(靜態(tài)鏈接,使用的時(shí)候需要lib)
#ifdef __cplusplus
#define EXPORT extern "C"__declspec(dllexport)
#else
#define EXPORT __declspec(dllexport)
#endif
EXPORT int HelloWorld()
{
cout << "hello world" << endl;
return 0;
}
第二種是為工程創(chuàng)建def文件,生成不需要lib的dll文件:
如下:(先生成一個(gè)def文件)
LIBRARY "computer"
EXPORTS
add PRIVATE
而在代碼里只需要用:
在DllMain 前面加上你自己要導(dǎo)出的函數(shù):
int add(int x,int y)
{
return(x + y);
}
而在使用的時(shí)候:
HMODULE hDll = ::LoadLibrary(TEXT("computer.dll"));
//typedef int pHelloWorld();
//pHelloWorld *pHello = (pHelloWorld *)::GetProcAddress(hDll, "HelloWorld");
typedef int (*pHelloWorld)();
pHelloWorld pHello = (pHelloWorld)::GetProcAddress(hDll, "HelloWorld");
int a = pHello();
2.上面是最簡(jiǎn)單的方式,弊端別人可以輕易的使用我們的dll。
如果我們要想著封裝下免得被其他人隨意使用,于是就有了導(dǎo)出函數(shù)指針,創(chuàng)建對(duì)象的思路了...具體闡述如下:
創(chuàng)建一個(gè)接口文件,供使用者參考。dll里面提供導(dǎo)出函數(shù)指針,創(chuàng)建這個(gè)接口的現(xiàn)實(shí)類對(duì)象,利用這個(gè)對(duì)象就可以使用其中的功能了。
a ) 創(chuàng)建一個(gè)publish文件(提供給使用者)
比如: computer_def.h
{
public:
virtual int add(int a, int b ) = 0;
virtual void del() = 0;
};
當(dāng)然不要忘記書寫你的def文件:
EXPORTS
DllGetClassObject PRIVATE
在dll中:
{
public:
virtual int add(int a , int b)
{
return a + b;
}
virtual void del()
{
delete this;
}
};
HRESULT __stdcall DllGetClassObject(Icomputer** ppv)
{
if( ppv == NULL )
return E_INVALIDARG;
*ppv = (Icomputer*)(new Ccomputer());
if( *ppv == NULL )
return E_OUTOFMEMORY;
return S_OK;
}
完成接口實(shí)現(xiàn)。提供導(dǎo)出函數(shù)。
在使用的工程中,記得引入頭文件 computer_def.h文件,然后:
HMODULE hDll = ::LoadLibrary(TEXT("computer.dll"));
typedef HRESULT (__stdcall *PFN_DllGetClassObject)(Icomputer** ppv);
PFN_DllGetClassObject pDllGetClassObject = (PFN_DllGetClassObject)::GetProcAddress(hDll, "DllGetClassObject");
if(NULL == pDllGetClassObject)
{
//nRet = STATUS_SEVERITY_ERROR;
}
// 創(chuàng)建接口
HRESULT hRet = pDllGetClassObject(&pComputer);
使用的時(shí)候:
int iRet = pComputer->add(iNum_1,iNum_2);
pComputer->del();
記得在使用完畢時(shí),FreeLibrary(hDll); 釋放資源。