[dll] 在 C++ 中使用 LoadLibraryA 或 LoadLibraryW 來調用 dll 中的函式

此篇文章演示如何在 Visual C++ 中,使用 LoadLibraryA 或 LoadLibraryW 來調用 dll。

(環境:Windows 10, Visual Studio 2017)
  1. 先寫一個 dll,詳細步驟說明請參考:『[dll] 用 Visual Studio 2017 寫一個包含 DllMain 的 dll。
  2. 開啟 Visual Studio 2017,新開一個專案『File → New → Project』或組合鍵『Ctrl+Shift+N』,點擊『Visual C++』之下的『Windows Desktop』,選擇『Windows Desktop Wizard』,在 Name 輸入好專案名稱後,按『OK』進到下個步驟。
  3. Application type 選『Console Application(.exe)』,Addtional options 都不用勾!按下『OK』就會建立好一個專案,預設會自動開啟專案中的『{專案名}.cpp』。
  4. 將下面的程式碼貼到『{專案名}.cpp』中,(參考原碼:Git)
    #include <iostream>
    #include <windows.h>
    
    typedef void(*voidFun)();
    
    int main()
    {
    	HMODULE hDll = LoadLibraryA("dllMainAndFun.dll");
    
    	voidFun pHelloWorldFun = (void(*)())GetProcAddress(hDll, "helloWorldFun");
    
    	pHelloWorldFun();
    
    	return 0;
    }
    
  5. 將要匯入的 dll 放到解決方案中的 Debug 資料夾下,因為 Debug 模式編譯出來的執行檔都存在此處。
  6. 按下 F5,開始 Debug 模式,看到彈出視窗(MessageBoxA/MessageBoxW),就代表載入成功了!顯示順序應為
    1. 程序建立時被呼叫
    2. 此函式呼叫成功
    3. 程序退出時被呼叫

留言

這個網誌中的熱門文章

[Hyper-V] 讓 Windows 可以吃到超過 16TB 的硬碟!