SOFTIST 程方法筆記 目録

直接从DLL调用函数(VC++)

本文记述通过GetProcAddress()函数,直接从DLL里取出函数的地址,进行调用的方法将使用下面列举的三个API

1.把包含要执行的函数的DLL装入内存,取出句柄
HMODULE LoadLibrary(LPCTSTR lpFileName);

2.用函数名或函数序号,取得该函数的地址
FARPROC GetProcAddress(HMODULE hModule, LPCSTR lpProcName);

3.释放DLL。
BOOL FreeLibrary(HMODULE hModule);

例:直接从user32.dll呼调MessageBox函数

/*
int MessageBox(
  HWND hWnd, // handle of owner window
  LPCTSTR lpText, // address of text in message box
  LPCTSTR lpCaption, // address of title of message box
  UINT uType // style of message box
);
*/

typedef int (__stdcall* MSBOX_FUNC)(HWND , LPCTSTR , LPCTSTR , UINT);

void CTestDlg::OnButton1() 
{
     HINSTANCE hinstDLL;
    MSBOX_FUNC pProc;
     hinstDLL = LoadLibrary("user32.dll");
    if (NULL != hinstDLL)
    {
         pProc = (MSBOX_FUNC)GetProcAddress(hinstDLL, "MessageBoxA");
        if (NULL != pProc)
            pProc(m_hWnd, "信息框已经显示出来了。", "通知", MB_OK);
         FreeLibrary(hinstDLL);    
    }
}