Can a Windows dll retrieve its own filename?
Asked Answered
I

2

34

A Windows process created from an exe file has access to the command string that invoked it, including its file's path and filename. eg. C:\MyApp\MyApp.exe --help.

But this is not so for a DLL invoked via LoadLibrary. Does anyone know of a way for a function loaded via DLL to find out what its path and filename are?

Specifically, I'm interested in a solution using the Delphi Programming Language, but I suspect that the answer would be pretty much the same for any language.

Indium answered 5/8, 2008 at 9:34 Comment(1)
"A Windows process created from an exe file has access to the command string that invoked it, including its file's path and filename." - That's not correct. It is a convention only. Have a look at the documentation for CreateProcessW() to learn how to launch a process that receives a command line with arbitrary content.Amitie
P
41

I think you're looking for GetModuleFileName.

http://www.swissdelphicenter.ch/torry/showcode.php?id=143:

{
  If you are working on a DLL and are interested in the filename of the
  DLL rather than the filename of the application, then you can use this function:
}

function GetModuleName: string;
var
  szFileName: array[0..MAX_PATH] of Char;
begin
  FillChar(szFileName, SizeOf(szFileName), #0);
  GetModuleFileName(hInstance, szFileName, MAX_PATH);
  Result := szFileName;
end;

Untested though, been some time since I worked with Delphi :)

Pula answered 5/8, 2008 at 9:37 Comment(2)
As of Delphi XE, GetModuleName is defined in the System.pas unitGatekeeper
In Delphi 6, Windows is required in uses clause for definition of MAX_PATH.Ernieernst
G
1

Delphi XE+

In newer versions of Delphi, you can simply use the GetModuleName function from System.SysUtils. You simply pass in hInstance as the parameter.

So the full code would be GetModuleName(hInstance) to get the DLL filename path.

Older than Delphi XE

With older versions of Delphi, you need to write your own function for this:

function GetModuleName: string;
var
  sFileName: array[0..MAX_PATH] of Char;
begin
  FillChar(sFileName, SizeOf(sFileName), #0);
  GetModuleFileName(hInstance, sFileName, MAX_PATH);
  Result := sFileName;
end;
Georgeanngeorgeanna answered 10/2 at 12:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.