Delphi to C++ GetModuleBase function conversion?
I'm no delphi wizard but I found this function on a board and I need it badly for C++, Is there somebody who knows Delphi and C++ well enough to convert it?
function GetModuleBase(hProcID: Cardinal; lpModName: PChar):Cardinal;
var
hSnap: Cardinal;
tm: TModuleEntry32;
begin
result := 0;
hSnap := CreateToolHelp32Snapshot(TH32CS_SNAPMODULE, hProcID);
if hSnap <> 0 then
begin
tm.dwSize := sizeof(TModuleEntry32);
if Module32First(hSnap, tm) = true then
begin
开发者_运维技巧 while Module32Next(hSnap, tm) = true do
begin
if lstrcmpi(tm.szModule, lpModName) = 0 then
begin
result := Cardinal(tm.modBaseAddr);
break;
end;
end;
end;
CloseHandle(hSnap);
end;
end;
The following is untested, but should be close:
#include <windows.h>
#include <tlhelp32.h>
byte *getModuleBase(DWORD hProcId, TCHAR *lpModName)
{
byte *result = NULL;
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, hProcId);
if (hSnap)
{
MODULEENTRY32 tm;
tm.dwSize = sizeof(MODULEENTRY32);
if (Module32First(hSnap, &tm))
{
while (Module32Next(hSnap, &tm))
{
if (lstrcmpi(tm.szModule, lpModName) == 0)
{
result = tm.modBaseAddr;
break;
}
}
}
CloseHandle(hSnap);
}
return result;
}
Note that this code doesn't check the name of the first module. If you want to check the first module too, then you could try something like this:
if (Module32First(hSnap, &tm))
{
do
{
if (lstrcmpi(tm.szModule, lpModName) == 0)
{
result = tm.modBaseAddr;
break;
}
}
while (Module32Next(hSnap, &tm));
}
you could also use WinAPI's GetModuleHandle or GetModuleHandleEx, they do the same thing(and are probably safer than what you have), you would just cast the HANDLE to a BYTE* or DWORD or whatever else is needed
精彩评论