dll导出函数调用封装

来源:互联网 发布:孙笑侠 知乎 编辑:程序博客网 时间:2024/05/16 06:27

为了方便,备份

 

/********************************************************************
 created: 2012:24:4   12:22:40
 author:  Insert
 purpose: dll export functions encapsulation
*********************************************************************/
#ifndef __DLLEXPORT__H__F53BDD46_6C8D_4EB1_8E65_5ED75697F6B8__
#define __DLLEXPORT__H__F53BDD46_6C8D_4EB1_8E65_5ED75697F6B8__

#include <Windows.h>
#include <assert.h>

#include <Shlwapi.h>
#pragma comment(lib, "Shlwapi.lib")

#define __CALLINGCONVENTION __cdecl

typedef struct _SNAMEPFUNC
{
 FARPROC*  pFunc;
 LPSTR    lpName;
} _SNF;

#define EMETHOD(__ret, __name, __pd, __pr)\
private:\
 __ret(__CALLINGCONVENTION *_fn##__name)__pd;\
public:\
 inline static __ret __name __pd\
 {\
  assert(NULL != _Instance()->_fn##__name);\
  return _Instance()->_fn##__name __pr;\
 }

#define BEGIN_EFUNC_MAP {\
 _SNF __snf[] ={

#define EFUNC(__name) {(FARPROC *)&_fn##__name, #__name},

#define END_EFUNC_MAP(__hm)\
 };\
 int __n = sizeof(__snf) / sizeof(_SNF);\
 for(int i = 0; i < __n; i++)\
 {\
 *__snf[i].pFunc = ::GetProcAddress( __hm, __snf[i].lpName );\
  assert(NULL != *__snf[i].pFunc && "Unknown export function!");\
 }\
}

class CExportFucntions
{
 //Interface of dll exports
 EMETHOD(void, funnoparam, (), ());
 EMETHOD(int, funwithparam, (int p1, bool p2), (p1, p2));
public:

private:
 CExportFucntions() : _hmModule(NULL)
 {
  _Instance();
 }
 ~CExportFucntions(){};

 static CExportFucntions* _Instance()
 {
  static CExportFucntions __ef;
  return &__ef;
 }

 const static TCHAR* _szModulePath;
 HMODULE _hmModule;

 BOOL _Initialize()
 {
  TCHAR szDllPath[MAX_PATH] = {0};
  if (0 == ::GetModuleFileName(NULL, szDllPath, MAX_PATH))
  {
   assert(0 && "GetModuleFileName failed!");
   return FALSE;
  }
  if (FALSE == ::PathAppend(szDllPath, _szModulePath))
  {
   assert(0 && "GetModuleFileName failed!");
   return FALSE;
  }
  if (FALSE == ::PathFileExists(szDllPath))
  {
   assert(0 && "DLL is not exist!");
   return FALSE;
  }

  _hmModule = ::LoadLibrary(szDllPath);
  if (NULL == _hmModule)
  {
   assert(0 && "LoadLibrary failed!");
   return FALSE;
  }

  BEGIN_EFUNC_MAP
   EFUNC(funnoparam)
   EFUNC(funwithparam)
  END_EFUNC_MAP(_hmModule)

  return TRUE;
 }

 void _UnInitialize()
 {
  if (NULL != _hmModule)
  {
   ::FreeLibrary(_hmModule);
  }
 }
};

const TCHAR* CExportFucntions::_szModulePath = TEXT("..\\somedll.dll");

#endif

原创粉丝点击