'Detours - Hooking a Classes Member Function - Syntax for setting function offset of target?
For non class functions - I can simply declare the offset of the function to be detoured like:
typedef int (_cdecl* SomeFunc)(char* pBuffer, int size);
SomeFunc Real_SomeFunc = (SomeFunc)(0xCAFEBABE);
...
DetourAttach(&(PVOID&)Real_SomeFunc, (PVOID)Hook_SomeFunc);
Now, this gets hard with detouring member functions of classes - detours has a sample for this:
https://github.com/microsoft/Detours/blob/master/samples/member/member.cpp
That sample already defines the targets member function - but I dont I only know the offset in the binary im injecting my DLL into - so how do I convert this
void (CDetour::* CDetour::Real_Target)(void) =
(void (CDetour::*)(void))&CMember::Target;
to something like this:
void (CDetour::* CDetour::Real_Target)(void) =
(void (CDetour::*)(void))0xCAFEBABE;
I'm getting a compile error here
Any hints?
Solution 1:[1]
void (CDetour::* CDetour::Real_Target)(void) = (void (CDetour::*)(void))0xCAFEBABE;I'm getting a compile error here
Specifically, it's error C2440: 'type cast' : cannot convert from 'unsigned int' to 'void (__thiscall CDetour::* )(void). There are no conversions from integral values to pointer-to-member values. Conversion to member pointers is a non-trivial beast - they may or may not be simple memory addresses, depending on the type of member function and complexity of the class hierarchy. Multiple virtual inheritance adds extra fields to this pseudo data structure; aside from the code address, there's also re-basing information. The format of this data is compiler-specific.
For my purposes, I use this MSVC-specific macro:
/// Void pointer to Func pointer.
/// Assumes first four bytes should hold the address and rest be zero.
template<typename T> T VTOF(void* ptr)
{// fills in 4 bytes and zeroes the rest
T result = 0;
*(void**)&result = ptr;
return result;
}
Usage: ptr = VTOF<void (CDetour::*)(void)>((void*)0xCAFEBABE);
Now, this obviously won't work in real complex code, but I assume it'll be good enough to work in a call to the original in a hook. It's been a while since I've had to use this on member function pointers.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
