动态库加载方法

来源:互联网 发布:macbook安装软件找不到 编辑:程序博客网 时间:2024/04/30 15:15

Introduction
Have you ever got tired of loading Dynamic Link Libraries the long way, with the usual steps LoadLibrary, and GetProcAddress, then you have to check for each function address if they are NULL, and don't mention about casting the function pointer and hard ways that make your brain strain. And wish there was an easier way to get around things? Well this will just do that in a way and is about the easiest way I know of actually


 Collapse code snippet Copy Code

  1. //GetProcAddresses
  2. //Argument1: hLibrary - Handle for the Library Loaded
  3. //Argument2: lpszLibrary - Library to Load
  4. //Argument3: nCount - Number of functions to load
  5. //[Arguments Format]
  6. //Argument4: Function Address - Function address we want to store
  7. //Argument5: Function Name -  Name of the function we want
  8. //[Repeat Format]
  9. //
  10. //Returns: FALSE if failure
  11. //Returns: TRUE if successful
  12. BOOL GetProcAddresses( HINSTANCE *hLibrary, 
  13.     LPCSTR lpszLibrary, INT nCount, ... )
  14. {
  15.     va_list va;
  16.     va_start( va, nCount );
  17.     if ( ( *hLibrary = LoadLibrary( lpszLibrary ) ) 
  18.         != NULL )
  19.     {
  20.         FARPROC * lpfProcFunction = NULL;
  21.         LPSTR lpszFuncName = NULL;
  22.         INT nIdxCount = 0;
  23.         while ( nIdxCount < nCount )
  24.         {
  25.             lpfProcFunction = va_arg( va, FARPROC* );
  26.             lpszFuncName = va_arg( va, LPSTR );
  27.             if ( ( *lpfProcFunction = 
  28.                 GetProcAddress( *hLibrary, 
  29.                     lpszFuncName ) ) == NULL )
  30.             {
  31.                 lpfProcFunction = NULL;
  32.                 return FALSE;
  33.             }
  34.             nIdxCount++;
  35.         }
  36.     }
  37.     else
  38.     {
  39.         va_end( va );
  40.         return FALSE;
  41.     }
  42.     va_end( va );
  43.     return TRUE;
  44. }

So since we now have the main core to this article, lets now look at how to use this with a short sample that was compiled as a Windows console application.

 Collapse Copy Code

  1. #include <windows.h>
  2. typedef int ( WINAPI *MESSAGEBOX ) 
  3.     ( HWND , LPCSTRLPCSTRDWORD );
  4. typedef int ( WINAPI *MESSAGEBOXEX ) 
  5.     ( HWND , LPCSTRLPCSTRDWORD , WORD );
  6. void main(void)
  7. {
  8.     MESSAGEBOX lpfMsgBox = NULL;
  9.     MESSAGEBOXEX lpfMsgBoxEx = NULL;
  10.     HINSTANCE hLib;
  11.     if(GetProcAddresses( &hLib, "User32.dll", 2,
  12.         &lpfMsgBox, "MessageBoxA",
  13.         &lpfMsgBoxEx, "MessageBoxExA" ) )
  14.     {
  15.         lpfMsgBox( 0, "Test1""Test1", MB_OK );
  16.         lpfMsgBoxEx( 0, "Test2""Test2", MB_OK, 
  17.             MAKELANGID( LANG_ENGLISH, SUBLANG_ENGLISH_US ) );
  18.     }
  19.     if ( hLib != NULL )
  20.         FreeLibrary( hLib );
  21. }


 

原创粉丝点击