[kaze's test] プログラミングメモ →目次

DLLから関数を呼び出す(VC++)

DLLから関数を呼び出すために、次の三つの関数で、実現できます。

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);    
    }
}