C++批量載入動態庫函式方法
阿新 • • 發佈:2019-01-10
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;
boolisLoadedGigEDLL() { 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)(); }