9.11.2009

GetProcAddresses one time - DLL

蓄上篇 DLL。
這一篇VC++ Example: Loading DLLs LoadLibrary and GetProcAddress and FreeLibrary文章就有用這樣的方法:

BOOL GetProcAddresses( HINSTANCE *hLibrary,
LPCSTR lpszLibrary, INT nCount, ... )
{
va_list va;
va_start( va, nCount );

if ( ( *hLibrary = LoadLibrary( lpszLibrary ) )
!= NULL )
{
FARPROC * lpfProcFunction = NULL;
LPSTR lpszFuncName = NULL;
INT nIdxCount = 0;
while ( nIdxCount < nCount )
{
lpfProcFunction = va_arg( va, FARPROC* );
lpszFuncName = va_arg( va, LPSTR );
if ( ( *lpfProcFunction =
GetProcAddress( *hLibrary,
lpszFuncName ) ) == NULL )
{
lpfProcFunction = NULL;
return FALSE;
}
nIdxCount++;
}
}
else
{
va_end( va );
return FALSE;
}
va_end( va );
return TRUE;
}

使用方法就是:

#include <windows.h>

typedef int ( WINAPI *MESSAGEBOX )
( HWND , LPCSTR, LPCSTR, DWORD );
typedef int ( WINAPI *MESSAGEBOXEX )
( HWND , LPCSTR, LPCSTR, DWORD , WORD );

void main(void)
{
MESSAGEBOX lpfMsgBox = NULL;
MESSAGEBOXEX lpfMsgBoxEx = NULL;
HINSTANCE hLib;
if(GetProcAddresses( &hLib, "User32.dll", 2,
&lpfMsgBox, "MessageBoxA",
&lpfMsgBoxEx, "MessageBoxExA" ) )
{
lpfMsgBox( 0, "Test1", "Test1", MB_OK );
lpfMsgBoxEx( 0, "Test2", "Test2", MB_OK,
MAKELANGID( LANG_ENGLISH, SUBLANG_ENGLISH_US ) );
}
if ( hLib != NULL )
FreeLibrary( hLib );
}

但是他還是用了typedef,其實直接宣告function pointer就可以了。

沒有留言: