C++批量加载动态库函数方法

1、枚举定义
enum
  {
    // 0 - GigE DLL (implicitly called)
    Func_isVersionCompliantDLL,
    Func_isDriverAvailable,

  }                                                  
  SVGigE_FUNCTION;


2、函数管理器:定义函数指针、ID(使用枚举)、函数名
struct _GigEFunc
{
  FARPROC function_pointer;
  SVGigE_FUNCTION function_id;
  char *function_name;
}
GigEFunc[] =
{
  // 0 - GigE DLL (implicitly called)
  NULL, Func_isVersionCompliantDLL,                     "isVersionCompliantDLL",
  NULL, Func_isDriverAvailable,                        "isDriverAvailable",
}

3、加载动态库,初始化函数指针
HINSTANCE GigEDLL = NULL;

bool
isLoadedGigEDLL() { if( NULL == GigEDLL ) { // Try to load GigE DLL GigEDLL = LoadLibrary(SVGigE_DLL); // Check DLL availability if( NULL == GigEDLL ) return false; } // Check if size of function table matches the number of imported functions int FunctionCount = sizeof(GigEFunc) / sizeof(struct _GigEFunc); if( FunctionCount != Func_isVersionCompliantDLL_consistency_check + 1 ) return false; // Obtain CameraContainer procedure addresses bool function_loaded = true; for( int function_index = Func_isVersionCompliantDLL; function_index < (sizeof(GigEFunc) / sizeof(struct _GigEFunc)); function_index++ ) { GigEFunc[function_index].function_pointer = GetProcAddress(GigEDLL, GigEFunc[function_index].function_name); // Check if function was found if( NULL == GigEFunc[function_index].function_pointer ) function_loaded = false; } // Check if all function pointers could successfully be obtained from the DLL if( function_loaded == false ) return false; else return true; }

4、定义函数指针

typedef SVGigE_RETURN
(*TFunc_isVersionCompliantDLL)(SVGigE_VERSION *DllVersion,
                               SVGigE_VERSION *ExpectedVersion);

typedef SVGigE_RETURN(*TFunc_isDriverAvailable)();
5、外部访问函数接口
SVGigE_RETURN
isVersionCompliantDLL(SVGigE_VERSION *DllVersion, 
                      SVGigE_VERSION *ExpectedVersion)
{
  // Check DLL availability
  if( NULL == GigEDLL )    //HINSTANCE  GigEDLL = NULL  hInstance是操作系统分配给实例的指针. 程序根据hInstance访问其相应的内存空间
  {
    // Try to load SVGigE DLL
    if( !isLoadedGigEDLL() )
      return SVGigE_DLL_NOT_LOADED;
  }

  // Pass through function call to DLL
 //
 // 2011-08-22/EKantz: check consistency of the whole function pointer 
 //                    table by calling the last function in that table.
 //
  return ((TFunc_isVersionCompliantDLL)
  GigEFunc[Func_isVersionCompliantDLL_consistency_check].function_pointer)(DllVersion, ExpectedVersion);
}

SVGigE_RETURN
isDriverAvailable()
{
  // Check DLL availability
  if( NULL == GigEDLL )
  {
    // Try to load SVGigE DLL
    if( !isLoadedGigEDLL() )
      return SVGigE_DLL_NOT_LOADED;
  }

  // Pass through function call to DLL
  return ((TFunc_isDriverAvailable)
  GigEFunc[Func_isDriverAvailable].function_pointer)();
}


 

 

原文地址:https://www.cnblogs.com/profession/p/10251589.html