Dll库的辅助类

/********************************************************************
 author  :   Clark/陈泽丹
 created :   2013-5-8
 purpose :   DLL辅助类
*********************************************************************/

#pragma once
#include <Windows.h>
#include <string>


template< class _IUtil >
class DllHelper
{
public:
	//需要dll定义 extern "C" __declspec(dllexport) _IUtil*  GetDLLAPI() 才可用
	DllHelper( LPCSTR _dll_name ) throw( std::string ): mh_dll(NULL),mp_util(NULL),FUN_NAME("GetDLLAPI") 
	{
		try
		{
			//第一次调用时未加载dll,下面进行加载dll
			string error = "";
			mh_dll = ::LoadLibrary(_dll_name);
			if( NULL == mh_dll )
			{
				error = "Can't load ";
				error += _dll_name;
				throw error;
			}
			ProcDLLFun proc = (ProcDLLFun)::GetProcAddress(mh_dll,FUN_NAME);
			if( NULL == proc )
			{
				error = _dll_name;
				error += " Can't GetProcAddress( ";
				error += FUN_NAME;
				error += " )";
				throw error;
			}
			mp_util = proc();
			if( NULL == mp_util )
			{
				error = FUN_NAME;
				error += " Error ! ";
				throw error;
			}
		}
		catch (string err) 
		{
			throw err;
		}
		catch(...)
		{
			throw "DllHelper Unknown Error!";
		}
	}

	~DllHelper()
	{
		if ( NULL != mp_util )
		{
			mp_util->Release();
			mp_util = NULL;			
		}
		if ( NULL != mh_dll )
		{
			::FreeLibrary(mh_dll); 
			mh_dll = NULL; 
		}
	}

	//重载->,将helper对象的引用直接转为接口的引用
	_IUtil* operator -> ()
	{ 
		return mp_util; 
	}

	//判断接口指针是否有效
	BOOL IsValid(){ return ( NULL != mp_util ); }

private:
	typedef			_IUtil* (*ProcDLLFun)();
	const char		*FUN_NAME;
	_IUtil			*mp_util;							//接口对象
	HINSTANCE		mh_dll;								//动态链接库加载与否标志
};

你可能感兴趣的:(Dll库的辅助类)