c++functionclassvmt

How to determine count of VMT pointers


using Visual C++ compiler every class object have VMT ( first pointer in object) which is the pointer to array of pointers to every method in class. Using code like this:

TestObject * object = new TestObject();
void** VMT = (void**)object;
int TestCount = 100;

for( int i = 0; i < TestCount; i ++ )
{
     printf("%d function: %p\r\n", (i+1), VMT[i] );
}

This code enumerates first 100 functions in class, but how can i determine how many those pointers class have considering that i don't have class definition? How to find out it dynamically?

Thanks!


Solution

  • Just don't do this.

    Firstly, a class that has no virtual members has no V-table, hence your attempt to fetch it will at best give an invalid pointer and at worst crash.

    Secondly, even if you do get it, you'll only find pointers to virtual member functions in it, normal functions aren't placed in the V-table.

    Thirdly, while I do note that you're using MSVC, so portability is less of an issue, this is hideously non-portable. I remember back to a very interesting object oriented system I used for the one game I wrote that published on the Sega Genesis. This was all done in 68K assembler, back in about 1995, including a V-table. Due to interesting memory constraints, all V-tables lived miles away from their class instances, in a special area of the first 64K page of memory. We had some gnarly linker trickery to hook everything up and make it all work.

    My point being that your line of code to go and fetch VMT may not wind up pointing at the V-table at all. The workings of this are implementation dependent, the compiler writer is at liberty to do it any way they want, as long as the end product works correctly according to the standard.

    And the final question? Why? What problem are you trying to solve that requires digging around like this in places most programmers stay well away from.