Delphi 開發 DLL 供 C# 呼叫時,GetCurrentDir 取得的是呼叫端 EXE 所在目錄,而非 DLL 自身目錄。
GetModuleFileName APIfunction GetDLLPath: string;
var
Buffer: array[0..MAX_PATH] of Char;
Len: Integer;
begin
Len := GetModuleFileName(HInstance, Buffer, MAX_PATH);
SetString(Result, Buffer, Len);
Result := ExtractFilePath(Result); // 只要目錄部分
end;
| 函數 | 參數 | 回傳 | 說明 |
|---|---|---|---|
GetModuleFileName | HInstance (DLL 模組句柄) | 完整路徑含檔名 | HInstance 為 DLL 自身載入基址 |
GetCurrentDir | 無 | 目前工作目錄 | 隨呼叫端進程而變 |
ParamStr(0) | 無 | EXE 完整路徑 | 僅適用於 EXE,DLL 中回傳呼叫端 EXE 路徑 |
[DllImport("MyDelphi.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern void GetDLLPath(StringBuilder path, int capacity);
// 使用
var sb = new StringBuilder(260);
GetDLLPath(sb, sb.Capacity);
string dllDir = Path.GetDirectoryName(sb.ToString());
MAX_PATH = 260,長路徑需加 \\?\ 前綴\,跨平台建議用 PathDelim 常數CharSet.Ansi 需對應 AnsiString