C, C++
Get DLL path at run time
dozob
2021. 10. 5. 23:41
#include <stdlib.h>
#include <libloaderapi.h>
LPCWSTR GetThisDllPath()
{
static wchar_t s_wszMyPath[_MAX_PATH] = { 0, };
if (!s_wszThisPath[0])
{
DWORD dwFlags = GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
| GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT;
HMODULE hModule;
if (!::GetModuleHandleExW(dwFlags, (LPCWSTR)&GetThisDllPath, &hModule))
{
int rv = ::GetLastError();
fprintf(stderr, "GetModuleHandleEx failed, error = %d\r\n", rv);
return nullptr;
}
if (!::GetModuleFileNameW(hModule, s_wszMyPath, _MAX_PATH))
{
int rv = ::GetLastError();
fprintf(stderr, "GetModuleFileName failed, error = %d\r\n", rv);
return nullptr;
}
}
return s_wszThisPath;
}
#include "pch.h"
wchar_t s_wszMyPath[_MAX_PATH];
BOOL APIENTRY DllMain(
HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
::GetModuleFileNameW(hModule, s_wszMyPath, _MAX_PATH);
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
HMOUDLE hModule = &__ImageBase;
wchar_t wszMyPath[_MAX_PATH];
::GetModuleFileNameW(hModule, wszMyPath, _MAX_PATH);