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