我希望能够从dll代码中获取其目录(或文件)路径(而不是程序的.exe文件路径)。
我已尝试过几种方法:
GetCurrentDir
- 获取当前目录路径。
GetModuleFileName
- 获取可执行文件的路径。
那么如何找出代码所在的dll呢?
我正在寻找类似于C#的Assembly.GetExecutingAssembly
的东西。
GetModuleHandleEx
函数获取 DLL 中静态函数的句柄。你可以在这里找到更多信息:here。GetModuleFileName
从刚获得的句柄中取得路径。有关该调用的更多信息,请参见此处。char path[MAX_PATH];
HMODULE hm = NULL;
if (GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCSTR) &functionInThisDll, &hm) == 0)
{
int ret = GetLastError();
fprintf(stderr, "GetModuleHandle failed, error = %d\n", ret);
// Return or however you want to handle an error.
}
if (GetModuleFileName(hm, path, sizeof(path)) == 0)
{
int ret = GetLastError();
fprintf(stderr, "GetModuleFileName failed, error = %d\n", ret);
// Return or however you want to handle an error.
}
// The path variable should now contain the full filepath for this DLL.
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
....
TCHAR DllPath[MAX_PATH] = {0};
GetModuleFileName((HINSTANCE)&__ImageBase, DllPath, _countof(DllPath));
__ImageBase
变量的未来兼容性有何评论? - AjayGetModuleFileName()
在 DLL 的代码内部运行良好。 只需确保不要将第一个参数设置为 NULL
,因为这会获取调用进程的文件名。 您需要指定 DLL 的实际模块实例。 您可以在 DLL 的 DllEntryPoint()
函数中获取该实例作为输入参数,只需将其保存到某个变量中以备将来使用。
这是一份Unicode修订版的最受欢迎的答案:
CStringW thisDllDirPath()
{
CStringW thisPath = L"";
WCHAR path[MAX_PATH];
HMODULE hm;
if( GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPWSTR) &thisDllDirPath, &hm ) )
{
GetModuleFileNameW( hm, path, MAX_PATH );
PathRemoveFileSpecW( path );
thisPath = CStringW( path );
if( !thisPath.IsEmpty() &&
thisPath.GetAt( thisPath.GetLength()-1 ) != '\\' )
thisPath += L"\\";
}
else if( _DEBUG ) std::wcout << L"GetModuleHandle Error: " << GetLastError() << std::endl;
if( _DEBUG ) std::wcout << L"thisDllDirPath: [" << CStringW::PCXSTR( thisPath ) << L"]" << std::endl;
return thisPath;
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
TCHAR dllFilePath[512 + 1] = { 0 };
GetModuleFileNameA(hModule, dllFilePath, 512)
}
break;
case DLL_THREAD_ATTACH: break;
...
dllFilePath将包含当前dll代码加载的路径。在这种情况下,hModule由加载dll的进程传递。
HMODULE hMod;
std::wstring PathAndName;
std::wstring OnlyPath;
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;
const int BUFSIZE = 4096;
wchar_t buffer[BUFSIZE];
if (::GetModuleFileNameW(hMod, buffer, BUFSIZE - 1) <= 0)
{
return TRUE;
}
PathAndName = buffer;
size_t found = PathAndName.find_last_of(L"/\\");
OnlyPath = PathAndName.substr(0, found);
return TRUE;
}
SysUtils.GetModuleName(hInstance); //Works; hInstance is a special global variable
SysUtils.GetModuleName(0); //Fails; returns the name of the host exe process
SysUtils.GetModuleName(GetModuleFilename(nil)); //Fails; returns the name of the host exe process
如果你的Delphi没有SysUtils.GetModuleName,它可以声明为:
function GetModuleName(Module: HMODULE): string;
var
modName: array[0..32767] of Char; //MAX_PATH is for a single filename; paths can be up to 32767 in NTFS - or longer.
begin
{
Retrieves the fully qualified path for the file that contains the specified module.
The module must have been loaded by the current process.
}
SetString(Result, modName, GetModuleFileName(Module, modName, Length(modName)));
end;
我(就我的情况而言)正在编写那些揭示了易于使用的 DllMain 方法的人。 任务是查找当前运行在 dll 中的线程的机器位数。为了绝对确定,我还想要运行中的 dll 和 exe 的名称。调用者的名称通过 NULL 参数找到:
char exePat[MAX_PATH] = { 0 }; GetModuleFileName(NULL, exePat, MAX_PATH);
使用 DllMain 的 hModule 感觉是找到 dll 名称和机器位数的最完整和可靠的方式。代码被发现,以便仅需要获取“机器”模块即可。 这是带出其名称以供调试目的的部分。
BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason,LPVOID lpReserved ) {
char path[MAX_PATH] = { 0 };
GetModuleFileNameA(hModule, path, MAX_PATH);
PIMAGE_DOS_HEADER startPoint = (PIMAGE_DOS_HEADER)hModule;
PIMAGE_NT_HEADERS pNtHeaders = (PIMAGE_NT_HEADERS)((LPBYTE)startPoint + startPoint->e_lfanew);
PIMAGE_FILE_HEADER fileHeader = &pNtHeaders->FileHeader;
short machine = fileHeader->Machine;
////0x8664 is 64bit 0x14c is 32bit.
int stop = 0;
return TRUE;
}
我想要实现类似的功能,但是希望将相似的函数制作成一个.dll文件 - 但是这样你就不能使用__ImageBase,因为它是特定于包含函数的那个.dll文件的。我甚至尝试过覆盖方法。
GetDllPath( HMODULE hDll = (HMODULE) __ImageBase)
但那也没有起作用。(由于某种原因在此之后返回应用程序路径。)
然后我想到了一个办法——为什么不使用VirtualQuery,使用函数指针并从中获取HMODULE。但是再次出现了问题——如何获取调用者的函数指针?
现在回到调用堆栈的确定上——我不会打扰您处理所有肮脏的细节,只需跟随所引用链接的链接即可。
以下是整个代码快照:
//
// Originated from: https://sourceforge.net/projects/diagnostic/
//
// Similar to windows API function, captures N frames of current call stack.
// Unlike windows API function, works with managed and native functions.
//
int CaptureStackBackTrace2(
int FramesToSkip, //[in] frames to skip, 0 - capture everything.
int nFrames, //[in] frames to capture.
PVOID* BackTrace //[out] filled callstack with total size nFrames - FramesToSkip
)
{
#ifdef _WIN64
CONTEXT ContextRecord;
RtlCaptureContext(&ContextRecord);
UINT iFrame;
for (iFrame = 0; iFrame < (UINT)nFrames; iFrame++)
{
DWORD64 ImageBase;
PRUNTIME_FUNCTION pFunctionEntry = RtlLookupFunctionEntry(ContextRecord.Rip, &ImageBase, NULL);
if (pFunctionEntry == NULL)
{
if (iFrame != -1)
iFrame--; // Eat last as it's not valid.
break;
}
PVOID HandlerData;
DWORD64 EstablisherFrame;
RtlVirtualUnwind(0 /*UNW_FLAG_NHANDLER*/,
ImageBase,
ContextRecord.Rip,
pFunctionEntry,
&ContextRecord,
&HandlerData,
&EstablisherFrame,
NULL);
if(FramesToSkip > (int)iFrame)
continue;
BackTrace[iFrame - FramesToSkip] = (PVOID)ContextRecord.Rip;
}
#else
//
// This approach was taken from StackInfoManager.cpp / FillStackInfo
// http://www.codeproject.com/Articles/11221/Easy-Detection-of-Memory-Leaks
// - slightly simplified the function itself.
//
int regEBP;
__asm mov regEBP, ebp;
long *pFrame = (long*)regEBP; // pointer to current function frame
void* pNextInstruction;
int iFrame = 0;
//
// Using __try/_catch is faster than using ReadProcessMemory or VirtualProtect.
// We return whatever frames we have collected so far after exception was encountered.
//
__try {
for (; iFrame < nFrames; iFrame++)
{
pNextInstruction = (void*)(*(pFrame + 1));
if (!pNextInstruction) // Last frame
break;
if (FramesToSkip > iFrame)
continue;
BackTrace[iFrame - FramesToSkip] = pNextInstruction;
pFrame = (long*)(*pFrame);
}
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
}
#endif //_WIN64
iFrame -= FramesToSkip;
if(iFrame < 0)
iFrame = 0;
return iFrame;
} //CaptureStackBackTrace2
//
// Gets .dll full path or only directory.
//
CStringW GetDllPath( bool bPathOnly /* = false */ )
{
void* pfunc = &GetDllPath;
wchar_t path[MAX_PATH] = { 0 };
MEMORY_BASIC_INFORMATION info;
HMODULE hdll;
CaptureStackBackTrace2(1, 2, &pfunc);
// Get the base address of the module that holds the current function
VirtualQuery(pfunc, &info, sizeof(MEMORY_BASIC_INFORMATION));
// MEMORY_BASIC_INFORMATION::AllocationBase corresponds to HMODULE
hdll = (HMODULE)info.AllocationBase;
// Get the dll filename
if ( !GetModuleFileName( hdll, path, MAX_PATH ) )
return L"";
if ( bPathOnly )
{
wchar_t* p = wcsrchr( path, '\\' );
if ( p )
*p = 0;
}
return path;
} //GetDllPath
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
标志的情况下,lpModuleName
可能不仅仅是本地函数。它也可能是 (本地)静态变量 的地址。 - Janusz LenarPathRemoveFileSpec
也是你的朋友。它可以帮助你删除文件路径中的文件名部分。 - zar