Get DLL path at runtime
I want to get a dll's directory (or file) path from within its code. (not the program's .exe file path)
I've tried a few methods I've found:
GetCurrentDir
- gets the current directory path.
GetModuleFileName
- gets the executable's path.
So how can i find out in which dll the code is in ?
I'm looking for something similar to C#'s Assembly.GetExecutingAssembly
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
....
WCHAR DllPath[MAX_PATH] = {0};
GetModuleFileNameW((HINSTANCE)&__ImageBase, DllPath, _countof(DllPath));
I would use the GetModuleHandleEx
function and get the handle to a static function in your DLL. You find more infos here.
After that you can use GetModuleFileName
to get the path from the handle you just obtained. More infos are here.
A complete example:
char path[MAX_PARAM];
HMODULE hm = NULL;
if (!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCSTR) &localFunc,
&hm))
{
int ret = GetLastError();
fprintf(stderr, "GetModuleHandle returned %dn", ret);
}
GetModuleFileNameA(hm, path, sizeof(path));
// path variable should now contain the full filepath to localFunc
GetModuleFileName()
works fine from inside the DLL's codes. Just be sure NOT to set the first parameter to NULL
, as that will get the filename of the calling process. You need to specify the DLL's actual module instance instead. You get that as an input parameter in the DLL's DllEntryPoint()
function, just save it to a variable somewhere for later use when needed.
上一篇: 托管C DLL调用C#DLL,FileNotFoundException
下一篇: 运行时获取DLL路径