Delphi程序在Linux下获取自身程序的路径信息,不像Winsows下有现成函数调用,需要绕一下。
uses System.Classes,
{$IFDEF MSWINDOWS}
Winapi.Windows,
{$ENDIF MSWINDOWS}
{$IFDEF POSIX}
Posix.Dlfcn, Posix.Fcntl, Posix.SysStat, Posix.SysTime, Posix.SysTypes,
Posix.Locale, Posix.unistd,
{$ENDIF POSIX}
System.SysUtils;
// 获取自身绝对路径
function GetDLLModuleFilePath(): string;
var
ModuleName: string;
Info: dl_info;
path: array [0 .. 1023] of byte;
cnt, i: integer;
begin
{$IFDEF MSWINDOWS}
setlength(ModuleName, 255);
GetModuleFilename(HInstance, pchar(ModuleName), length(ModuleName));
result := pchar(ModuleName);
{$ENDIF MSWINDOWS}
{$IFDEF POSIX}
//使用readlink函数来获取
cnt := readlink('/proc/self/exe', @path[0], 1024);
if (cnt < 0) or (cnt >= 1024) thenexit('');
for i := 0 to cnt - 1 do
result := result + char(path[i]);
//dladdr函数只能获取到当前文件的相对路径
// if (dladdr(IntPtr(@GetDLLModuleFilePath), Info) <> 0) and (Info.dli_fname <> nil) then// ModuleName := string(Info.dli_fname);
// result := ModuleName;
{$ENDIF POSIX}
end;