动态链接库(dynamic link lib)加载的模板实现

本文介绍了如何使用模板类`CDllLoader`来管理动态链接库(DLL)的加载,特别是当多个DLL有相似的入口接口时。通过定义`typedef int (*pDll)(const char* pName, DllInterface *&pCallor)`,实现了动态库的加载、接口指针获取和资源释放。`CDllLoader`提供了`load`方法加载DLL,`Release`方法释放资源,以及重载操作符方便使用。" 101532758,6548427,Python+Selenium实现拉勾网自动投递简历脚本,"['Python', '自动化测试', 'Web自动化', 'Selenium']

当一个大的应用程序要加载不同动态库,但是这些动态库的入口接口相同或者相似,就需要用模板来管理加载动态库类。例如一个基于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; //接口对象,指向动态库中导出的类对象
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值