get the real address(or index in vTable) of virtual member function
c++, member-functions
Solution
Don't give up so easily!
While the other answers are correct in saying that the C++ language doesn't allow you to do this in a portable way, there's an important factor in your particular case that may make this a more reasonable thing to do.
The key is that ID3DXFont is a COM interface and the exact binary details of how those work are specified separately from the language used to access them. So while C++ doesn't say what you'll find at the other end of that pointer, COM does say that there's a vtable there with an array of function pointers in a specified order and with a specified calling convention. This allows me to tell you that the index of the DrawText function is 314 (DrawTextA) or 15 (DrawTextW) and that this will still be true in Visual C++ 28.0 many years from now. Or in GCC 8.3.1 for that matter: since COM is a binary interface specification, all compilers are supposed to implement it the same way (if they claim to support COM).
Have a look at the second link below for a ready-made implementation of COM function hooking using two different methods. Approach#2 is the closest to what you're asking for but I think you may want to consider the first one instead because it involves less voodoo.
Sources:
[http://msdn.microsoft.com/en-us/library/ms680573(v=vs.85).aspx] [http://www.codeproject.com/Articles/153096/Intercepting-Calls-to-COM-Interfaces] [http://goodrender.googlecode.com/svn/trunk/include/d3dx9core.h]
Problem
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.