0

使用 Visual C++ 编译器,每个类对象都有VMT(对象中的第一个指针),它是指向类中每个方法的指针数组的指针。使用这样的代码:

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] );
}

这段代码枚举了类中的前 100 个函数,但是考虑到我没有类定义,我如何确定类有多少指针?如何动态找出它?

谢谢!

4

1 回答 1

3

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.

于 2018-03-15T00:00:56.130 回答