2

I am compiling a c++ dll (and a shared object on Linux). The dll code reads data from binary files in the current directory where the dll itself is present (same directory as dll). This dll along with binary files can be copied to any location by the users.

What's the c++ function/API to get the absolute path of the DLL, from code running in the same DLL?

I am afraid that ".\" will be relative to the 3rd party executable (not the dll) to which my dll will be linked later. That's the reason I am trying to find out the path to dll at runtime. Is this the correct approach? I am asking as I have only seen the codes that read from the paths resolved at compile time.

  • When you say "the absolute path of the files relative to the DLL" I think you mean just "the absolute path of the files". I say this because "the path of the files relative to the DLL" is `.` by definition – Tim Randall Aug 05 '21 at 17:53

1 Answers1

1

On Windows, the module handle of the DLL is passed to DllMain:

BOOL WINAPI DllMain(
    HINSTANCE hinstDLL,  // handle to DLL module
    DWORD fdwReason,     // reason for calling function
    LPVOID lpReserved )  // reserved
{
    ...

You can then pass that handle to GetModuleFileName to get the full pathname of the DLL:

TCHAR filename [MAX_PATH];
GetModuleFileName (hinstDLL, filename, MAX_PATH);

You can then strip off the filename part to leave the name of the directory containing your DLL (exercise for the reader).

I don't know of any way to do this under Linux, but maybe someone else can provide an answer for that one.

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48
  • yes, correct. however file path can be longer than `MAX_PATH` (up to `MAXSHORT` chars) and instead `hinstDLL` we can use `&__ImageBase` if use *link.exe* for build – RbMm Aug 05 '21 at 18:37