[dll] 用 Visual Studio 2017 寫一個包含 DllMain 的 dll

此篇文章演示如何用 Visual Studio 2017 寫一個 dll,其包含 DllMain 與一個 dllexport 函數,若要知道如何在其它的 C++ 專案中使用,請參考『[dll] 在 C++ 中使用 LoadLibraryA 或 LoadLibraryW 來調用 dll 中的函式。』。

(環境:Windows 10, Visual Studio 2017)
  1. 先確認開發環境,開啟『Visual Studio Installer』,確認『Desktop development with C++』已安裝,才可進行下面的步驟。
  2. 開啟 Visual Studio 2017,新開一個專案『File → New → Project』或組合鍵『Ctrl+Shift+N』,點擊『Visual C++』之下的『Windows Desktop』,選擇『Windows Desktop Wizard』,在 Name 輸入好專案名稱後,按『OK』進到下個步驟。
  3. Application type 選『Dynamic Link Library(.dll)』,Addtional options 都不用勾!按下『OK』就會建立好一個專案,預設會自動開啟專案中的『dllmain.cpp』。
  4. 將下面的程式碼貼到『dllmain.cpp』中,(參考原碼:Git)
    // dllmain.cpp : Defines the entry point for the DLL application.
    #include "framework.h"
    #define DLLMAIN_API __declspec(dllexport)
    
    extern "C" DLLMAIN_API void helloWorldFun() 
    {
    	MessageBoxW(0, L"此函式呼叫成功", L"helloWorldFun", 0);
    }
    
    BOOL APIENTRY DllMain(HMODULE hModule,
    	DWORD  ul_reason_for_call,
    	LPVOID lpReserved
    )
    {
    	switch (ul_reason_for_call)
    	{
    	case DLL_PROCESS_ATTACH:
    		MessageBox(0, L"程序建立時被呼叫", L"DllMain", 0);
    		break;
    	case DLL_THREAD_ATTACH:
    		MessageBox(0, L"執行緒建立時被呼叫", L"DllMain", 0);
    		break;
    	case DLL_THREAD_DETACH:
    		MessageBox(0, L"執行緒退出時被呼叫", L"DllMain", 0);
    		break;
    	case DLL_PROCESS_DETACH:
    		MessageBox(0, L"程序退出時被呼叫", L"DllMain", 0);
    		break;
    	}
    	return TRUE;
    }
    
  5. 點擊功能選單『Build』→『Build Solution』,可在『Output』視窗看到下方提示,會在專案下的 Debug 資料夾產出 dll 檔案,檔名與專案名稱相同。
    1>------ Build started: Project: Project1, Configuration: Debug Win32 ------
    1>dllmain.cpp
    1>   Creating library C:\Users\wrxue\source\repos\Project1\Debug\Project1.lib and object C:\Users\wrxue\source\repos\Project1\Debug\Project1.exp
    1>Project1.vcxproj ->  C:\Users\wrxue\source\repos\Project1\Debug\Project1.dll 
    ========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
    
  6. 此時的 dll 就是包含 DllMain 與匯出一個函式『helloWorldFun』的 dll 檔案囉!

留言

這個網誌中的熱門文章

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