这适用于32位MSVC构建(这是一些生产代码的一个非常简化版本,已使用了一年多)。请注意,您的替换方法必须明确指定this
参数(指针)。
// you can get the VTable location either by dereferencing the
// first pointer in the object or by analyzing the compiled binary.
unsigned long VTableLocation = 0U;
// then you have to figure out which slot the function is in. this is easy
// since they're in the same order as they are declared in the class definition.
// just make sure to update the index if 1) the function declarations are
// re-ordered and/or 2) virtual methods are added/removed from any base type.
unsigned VTableOffset = 0U;
typedef void (__thiscall Base::*FunctionType)(const Base*);
FunctionType* vtable = reinterpret_cast<FunctionType*>(VTableLocation);
bool hooked = false;
HANDLE process = ::GetCurrentProcess();
DWORD protection = PAGE_READWRITE;
DWORD oldProtection;
if (::VirtualProtectEx(process, &vtable[VTableOffset], sizeof(int), protection, &oldProtection))
{
vtable[VTableOffset] = static_cast<FunctionType>(&ReplacementMethod);
if (::VirtualProtectEx(process, &vtable[VTableOffset], sizeof(int), oldProtection, &oldProtection))
hooked = true;
}
我不在乎你为什么要这样做。这是一个坏主意。不要这样做。 – abelenky 2009-10-09 06:36:29
@abelenky,这仅仅是为了教育目的。我想知道事情是如何工作的。 :) – mahesh 2009-10-09 06:38:05
@ Martin的评论是您可以为教育目的获得的最佳建议。否则 - 只要放弃,编译器对这个工作更好。 – LiraNuna 2009-10-09 06:54:10