深度搜索C++对象模型笔记

1.通过vtbl,调用class的成员函数.(操作平台:mac 64位系统)

#include <iostream>
#include <fstream>
#include <string>
using namespace std;


// template<typename ToType, typename FromType>
// void GetAddr(ToType &addr, FromType f)
// {
//     union
//     {
//         FromType _f;
//         ToType _t;
//     }ut;
//     ut._f = f;
//     addr = ut._t;
// }


//挨个字节显示内存数据
void showByteValue(char *p, int cnt)
{
    cout << "挨个字节显示内存数据" << endl;
    cout << "===============sizeof(char*)= " << sizeof(char*) << endl;
    
    for (int i = 0;i < cnt; ++i)
    {
        int *temp = (int*)(p+i);
        //cout << (void*)temp << ", " << *(p+i) << endl;
        printf("%p: 0x%X, \t%x\n", temp, *(p+i), *temp);
        if (i%8 == 7)
            printf("\n");
    }
    cout << "=========================" << endl;
}


class B
{
public:
    //B(){ cout << "init B ok!" << endl;      }
    //~B(){ cout << "release B ok!" << endl;  }
    virtual int show(){cout << "fucking shit, print b ok!" << endl; return 0; }
    int b;
    //char c;
};


class D : public B
{
public:
    D(){ cout << "D init over"; }
    virtual int show(){cout << "it is D now" << endl; return 0; }
    int d;
};


//显示vtbl里面的内容,然后直接调用成员函数,打印输出.
void showVtbl(long *p)
{
    cout << "=========================sizeof(long)= " << sizeof(long) << endl;
    cout << "显示vtbl里面的内容,然后直接调用成员函数,打印输出." << endl;
    long v = *p;
    
    long *vtbl = (long *)v;
    showByteValue((char*)vtbl, 16);
    
    long func_addr = *vtbl;
    
    printf("f addr= %lx\n", func_addr);
    int (*f) ();
    
    memcpy((void*)&f, (void*)&func_addr, 8);
    f();
    cout << "=========================" << endl;
}


int main(int argc, char **argv)
{
    B *pb = new B;
    D *pd = new D;
    pb->b = 0x12345678;
    pd->b = 0x81828384;
    pd->d = 0x91929394;
    
    cout << "sizeof(B)=" << sizeof(B) << ", sizeof(D)=" << sizeof(D) << endl;
    showByteValue((char*)pb, sizeof(B));
    printf("pointer: &(pb->b)= %p\n", &(pb->b));
    showByteValue((char*)pd, sizeof(D));
    printf("pointer: &(pd->d)= %p\n", &(pd->d));


    showVtbl((long*)pb);
    showVtbl((long*)pd);
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值