打印C++对象的virtual table
csdn看到一帖讨论virtual table,我不是太了解,稍微翻了点资料,原来C++对象的前4字节是指向vitural table 的指针。
于是尝试写一个打印vitural table 的函数,还挺管用
![div css xhtml xml Example Source Code](https://images.cnblogs.com/cnblogs_com/suyuan/quote.gif)
#include <iostream> using namespace std; class A { public: virtual void f1() { cout<<"A::f1()"<<endl; } }; class B :public A { public: virtual void f2() { cout<<"B::f1()"<<endl; } }; class C : public B { public: virtual void f2() { cout<<"C::f2()"<<endl; } }; void dump_vtable(const int *pObj){ typedef void (*pFun)(); int * const &pVTable = (int *)(*pObj); cout<<"VTable: 0x"<<hex<<*pVTable<<endl; void *pVoid = NULL; pFun fun; int i = 0; while(pVoid = (int *)(*(pVTable + i))){ fun = (pFun)pVoid; cout<<"func["<<i<<"]: address "<<(int *)(*(pVTable + i))<<" call..."<<endl; fun(); ++i; } } int main(int argc, char* argv[]) { B b; int *pb = (int *)(&b); dump_vtable(pb); return 0; }
另外,如果对象没有virtual函数,就不会有virtual table,对象直接从成员开始
![div css xhtml xml Example Source Code](https://images.cnblogs.com/cnblogs_com/suyuan/quote.gif)
class D{ public: int a; D():a(222){ } }; int main(int argc, char* argv[]) { D d; int *pd = (int *)(&d); cout<<hex<<pd<<" value:"<<dec<<(*pd); return 0; }