IMHO, the Lebaus remy answer is the best, but, like everyone else, it is not enough to display the DLL directory. I quote the original question: "I want to get the path to the directory (or file) of the DLL from its code. (Not the path to the program's .exe file). 'I will develop two functions inside the DLL, the first will return a fully qualified name, the second will be fully qualified path. Assume that the full name of the DLL is "C: \ Bert \ Ernie.dll", then the functions return "C: \ Bert \ Ernie.dll" and "C: \ Bert" respectively. As Remi and Jean-Marc noted. DllMain , the DllMain DLL input function, usually found in dllmain.cpp, provides a DLL library descriptor, which is often needed, so it will be saved in g hMod global variable:
HMODULE hMod; BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } hMod = hModule; return TRUE; }
Now, in the TestDll.cpp file, I define the GetFullyQualifiedNameOfDLL(wchar_t* PathFile) function GetFullyQualifiedNameOfDLL(wchar_t* PathFile) , which displays the full name, in our example "C: \ Bert \ Ernie.dll" and the GetFullyQualifiedPathToDLL(wchar_t * Path) function, which returns only the path here. "C : \ Bert '
// TestDll.cpp : Defines the exported functions for the DLL application.
These functions can be used inside a DLL. A user of this DLL can call these functions as follows:
void _tmain(int argc, TCHAR *argv[]) { wchar_t PathFile[MAX_PATH], Path[MAX_PATH]; GetFullyQualifiedNameOfDLL(PathFile); wprintf(L"Fully qualified name: %s\n", PathFile); //Split the fully qualified name to get the path and name std::wstring StdPath = PathFile; size_t found = StdPath.find_last_of(L"/\\"); wprintf(L"Path: %s, name: %s\n", StdPath.substr(0, found).c_str(), StdPath.substr(found + 1).c_str()); GetFullyQualifiedPathToDLL(Path); wprintf(L"Path: %s\n", Path); }
Dietrich Baumgarten Aug 31 '19 at 14:33 2019-08-31 14:33
source share