In c++ is there any way to get the real address of member function, or the index in vTable ?
Updated:
I don't know the INDEX in vTable and I don't know the address
Here's why I want to know this:
I want to hook the function ID3DXFont->DrawText of DirectX. If I know the index of the DrawText in the vTable, I can replace it to do the hook. But how to get the index? If it's able to get the the real address, I can search it in the vTable to get the index.
And not particularly ID3DXFont->DrawText, maybe some other functions in the future, so I'm trying to write a generic hook function.
Here's what I've tried so far:
#include <iostream>
using namespace std;
struct cls {
virtual int fn1() {
cout << "fn1 called" << endl;
return 1;
}
virtual int fn2() {
cout << "fn2 called" << endl;
return 2;
}
};
template <typename fn_t>
DWORD fn_to_addr(fn_t fn) { // convert function to DWORD for printing
union U {
fn_t fn;
DWORD addr;
};
U u;
u.fn = fn;
return u.addr;
}
int main() {
cls c;
DWORD addr = fn_to_addr(&cls::fn2);
cout << hex << addr << endl;
}
In debug mode, the code above outputs the address of jump table. And in release mode, the &cls::fn2 returns 0x00401058, which points to some optimized code:
00401058 . mov eax, dword ptr [ecx] // get vptr
0040105A . jmp dword ptr [eax+4] // jmp to the second function (fn2)
Both are not the real address. Anyway to do that?
Thanks.