打印C++对象的virtual table

csdn看到一帖讨论virtual table,我不是太了解,稍微翻了点资料,原来C++对象的前4字节是指向vitural table 的指针。

于是尝试写一个打印vitural table 的函数,还挺管用

 

 

div css xhtml xml Example Source Code Example Source Code [http://www.cnblogs.com/tomsheep/]
#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 Example Source Code [http://www.cnblogs.com/tomsheep/]
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;
}

原文链接: https://www.cnblogs.com/tomsheep/archive/2010/04/29/1723448.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    打印C++对象的virtual table

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/10489

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月6日 下午11:47
下一篇 2023年2月6日 下午11:47

相关推荐