動態連結庫(DLL)是 Windows 模組化程式設計的基石。Delphi 提供完整的 DLL 開發與呼叫支援,涵蓋靜態與動態兩大呼叫模式,並深度整合 Windows API。本文系統闡述呼叫機制、參數規範與核心 API 細節。
使用 external 宣告,DLL 在應用程式啟動階段由載入器自動載入。
function Instr(SourceStr: PChar; Check: Char): Integer; far; external 'UseStr';
透過 Windows API LoadLibrary、GetProcAddress、FreeLibrary 在運行時手動控制載入與釋放。
所有被呼叫函式必須採用 far 遠呼叫慣例(或編譯指令 {$F+})。
function MyFunc: Integer; far; external 'MyDLL';function MyFunc: Integer; far; external 'MyDLL' name 'InternalFunc';function MyFunc: Integer; far; external 'MyDLL' index 3;別名提供命名彈性;序數提升載入效能但維護成本較高(導出順序變更會失效)。
function LoadLibrary(LibFileName: PChar): THandle;
搜尋順序:
GetWindowsDirectory)GetSystemDirectory)GetModuleFileName)返回值:
常見錯誤碼對照:
| 碼 | 含義 |
|---|---|
| 0 | 系統記憶體不足、檔案損壞或非法調用 |
| 2 | 找不到指定檔案 |
| 3 | 找不到指定路徑 |
| 5 | 存取被拒(共享/網路保護錯誤) |
| 8 | 記憶體不足無法啟動應用程式 |
| 10 | Windows 版本不正確 |
| 11 | 可執行檔無效(非 Windows 應用或映像錯誤) |
| 20 | DLL 檔案無效 |
| 21 | 需要 32 位擴展 |
若模組已載入,LoadLibrary 僅遞增引用計數,不重複映射。
function GetProcAddress(Module: THandle; ProcName: PChar): TFarProc;
Module:LoadLibrary 返回句柄(nil 表當前模組)。ProcName:函式名稱字串指標**或**序數值(低字組)。exports 宣告完全一致。TFarProc),失敗返回 nil。procedure FreeLibrary(Module: THandle);
下一篇將呈現動態呼叫的完整實戰範例:字串搜尋函式的動態載入與強制型別轉換呼叫技巧。