1.创建dll工程
以创建win32 dll程序为例,一般有两种方式:
一种是建立lib链接方式的dll:(静态链接,使用的时候需要lib)
#ifdef __cplusplus
#define EXPORT extern "C"__declspec(dllexport)
#else
#define EXPORT __declspec(dllexport)
#endif
EXPORT int HelloWorld()
{
cout <
return 0;
}
第二种是为工程创建def文件,生成不需要lib的dll文件:
如下:(先生成一个def文件)
LIBRARY"computer"
EXPORTS
addPRIVATE
而在代码里只需要用:
在DllMain前面加上你自己要导出的函数:
int add(int x,int y)
{
return(x + y);
}
而在使用的时候:
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.上面是最简单的方式,弊端别人可以轻易的使用我们的dll。
如果我们要想着封装下免得被其他人随意使用,于是就有了导出函数指针,创建对象的思路了...具体阐述如下:
创建一个接口文件,供使用者参考。dll里面提供导出函数指针,创建这个接口的现实类对象,利用这个对象就可以使用其中的功能了。
a ) 创建一个publish文件(提供给使用者)
比如: computer_def.h
classIcomputer
{public:virtualintadd(inta,intb )=0;virtualvoiddel()=0;
};
当然不要忘记书写你的def文件:
LIBRARY"computer"EXPORTS
DllGetClassObject PRIVATE
在dll中:
classCcomputer :publicIcomputer
{public:virtualintadd(inta ,intb)
{returna+b;
}virtualvoiddel()
{
deletethis;
}
};
HRESULT __stdcall DllGetClassObject(Icomputer**ppv)
{if( ppv==NULL )returnE_INVALIDARG;*ppv=(Icomputer*)(newCcomputer());if(*ppv==NULL )returnE_OUTOFMEMORY;returnS_OK;
}
完成接口实现。提供导出函数。
在使用的工程中,记得引入头文件 computer_def.h文件,然后:
Icomputer*pComputer;
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;}//创建接口HRESULT hRet=pDllGetClassObject(&pComputer);
使用的时候:
int iRet = pComputer->add(iNum_1,iNum_2);
pComputer->del();
记得在使用完毕时,FreeLibrary(hDll); 释放资源。
posted on 2009-08-17 23:04 -274°C 阅读(923) 评论(0) 编辑 收藏 所属分类: C++