DllTest。
// Lib.h
#ifndef LIB_H
#define LIB_H
extern "C" __declspec(dllexport) int add(int x, int y);
#endif
// Lib.cpp
#include "Lib.h"
int add(int x, int y) { return x + y; }
// DllClient.cpp
#include <windows.h>
#include <iostream>
typedef int (*PFN_ADD)(int, int);
int main() {
HINSTANCE hDll = LoadLibrary(L"..\\Debug\\DllTest.dll");
if (!hDll) { std::cerr << "LoadLibrary 失敗:" << GetLastError(); return 1; }
PFN_ADD pAdd = (PFN_ADD)GetProcAddress(hDll, "add");
if (!pAdd) { std::cerr << "GetProcAddress 失敗"; FreeLibrary(hDll); return 1; }
std::cout << "2 + 3 = " << pAdd(2, 3) << '\n';
FreeLibrary(hDll);
return 0;
}
typedef 定義函數指標型別,確保參數/回傳型別一致。LoadLibrary 載入 DLL 至進程位址空間,回傳模組句柄。GetProcAddress 依「導出名稱」或「序數」取得函數位址。FreeLibrary 釋放參考計數,歸零時真正卸載。DllTest.lib、DllTest.dll 複製至呼叫端專案目錄。#pragma comment(lib, "DllTest.lib")
extern "C" __declspec(dllimport) int add(int, int);
int main() { std::cout << add(2, 3); }
#pragma comment(lib,...) 指示連結器引入 .lib。__declspec(dllimport) 告知編譯器此為 DLL 匯入符號,產生間接跳轉指令(效能微幅提升)。LoadLibrary/GetProcAddress,載入器自動處理。; Lib.def
LIBRARY DllTest
EXPORTS
add @1
Lib.def。Lib.h 可移除 __declspec(dllexport),僅保留 extern "C" int add(int, int);。MAKEINTRESOURCEA(1))取得函數位址。BOOL APIENTRY DllMain(HINSTANCE hModule, DWORD ul_reason, LPVOID) {
switch (ul_reason) {
case DLL_PROCESS_ATTACH: OutputDebugStringA("Process Attach\n"); break;
case DLL_THREAD_ATTACH: OutputDebugStringA("Thread Attach\n"); break;
case DLL_THREAD_DETACH: OutputDebugStringA("Thread Detach\n"); break;
case DLL_PROCESS_DETACH: OutputDebugStringA("Process Detach\n"); break;
}
return TRUE;
}
搭配 LoadLibrary/FreeLibrary 觀察 DebugView 輸出順序:
Process Attach
call add in dll:5
Process Detach
| 場景 | 推薦模式 | 理由 |
|---|---|---|
| 核心功能、永遠需要 | 靜態連結 | 簡單、載入器優化、無額外程式碼 |
| 外掛/插件架構 | 動態載入 | 執行期發現、載入、卸載 |
| 選用功能、體積大 | 動態載入 | 按需載入、節省記憶體 |
| 多版本相容 | 動態載入 | 依環境選擇載入不同 DLL |
| 系統 API、第三方 SDK | 靜態連結 | 穩定介面、標準部署 |
LoadLibrary 使用相對路徑時,工作目錄可能非預期 → 建議使用絕對路徑或 SetDllDirectory/AddDllDirectory。DllMain 禁區:勿在內部呼叫 LoadLibrary、CreateThread、CRT I/O、同步物件等。本文範例專案已打包於同方案中,下載即可直接建置體驗完整流程。