Whats the correct way to read a file in a dynamic link library

Viewed 174

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.

1 Answers

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.

Related