First, you are leaking the SnapShot
handle if Module32First()
fails.
Second, you are using the TCHAR
-based version of the Module32 API, but you are passing in wchar_t
Unicode data to compare the enumerated module data to. You have your project setup to MultiByte, which means TCHAR
maps to char
and TCHAR
-based APIs map to ANSI APIs.
So, you are actually calling the ANSI version of the Module32 API, ie MODULEENTRY32
maps to MODULEENTRY32A
, and Module32First()
/Module32Next()
map to Module32FirstA()
/Module32NextA()
.
You cannot pass char
data to wcscmp()
, and you cannot pass wchar_t
data to strcmp()
. So, if you continue using the ANSI APIs, then you MUST perform a data conversion at runtime in one direction or the other, either to:
Only then can you use an appropriate function to compare the two datas.
Since you are passing in wchar_t
data for comparison, you should explicitly call the Unicode version of the Module32 API, not the TCHAR
version. You do not have to set the whole project to Unicode in order to use Unicode APIs, eg:
void* GetModuleBaseAddress(const wchar_t* ModuleName, DWORD ProcessId)
{
HANDLE SnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, ProcessId);
if (SnapShot)
{
MODULEENTRY32W ModuleEntry = { 0 };
ModuleEntry.dwSize = sizeof(ModuleEntry);
if (Module32FirstW(SnapShot, &ModuleEntry))
{
do
{
if (wcscmp(ModuleEntry.szModule, ModuleName) == 0)
{
CloseHandle(SnapShot);
return ModuleEntry.modBaseAddr;
}
}
while (Module32NextW(SnapShot, &ModuleEntry));
}
CloseHandle(SnapShot);
}
return NULL;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…