当一个大的应用程序要加载不同动态库,但是这些动态库的入口接口相同或者相似,就需要用模板来管理加载动态库类。例如一个基于2个设备开发的应用程序,至少需要有2层,第一层是设备的驱动程序(用动态库DLL表示),第二层需要在初始化2个设备的时候同时加载这两个库。而这2个动态库入口接口一个参数为设备名,一个参数为设备所对应的对象接口。这个时候动态库入口函数就可以写成typedef int (*pDll)(const char* pName, DllInterface *&pCallor); DllInterface 为模板类声明。具体实现参考以下代码:
template<class DllInterface>
class CDllLoader
{
private:
typedef int (*pDll)(const char* pName, DllInterface *&pCallor);//动态库入口接口定义
//库资源的释放和接口指针释放
void Release()
{
if (m_interface != NULL)
{
m_interface = NULL;
}
if (hDll != NULL)
{
FreeLibrary(hDll);
hDll = NULL;
}
}
public:
CDllLoader()
{
hDll = NULL;
m_interface = NULL;
}
virtual ~CDllLoader()
{
Release();
}
int load(const char* szDllName,const char* szCreateFunctionName,const char* pClassName = NULL)
{
hDll = LoadLibrary(szDllName);
if (hDll)
{
return 1;
}
pDll *pCreate = (pDll)GetProcAddress(hDll,szCreateFunctionName);
if (pCreate == NULL)
{
Release();
return 2;
}
int nRet = pCreate(pClassName,m_interface);
if (nRet < 0)
{
Release();
return nRet;
}
return 0;
}
DllInterface* operator->()
{
return m_interface;
}
bool operator==(DllInterface* p)
{
return m_interface == p;
}
bool operator!=(DllInterface* p)
{
return m_interface != p;
}
bool operator!()
{
return !m_interface;
}
protected:
HINSTANCE hDll;//库实例对象
DllInterface *m_interface; //接口对象,指向动态库中导出的类对象
};