对于一个带有虚函数的类中,他的对象的内存结构可以参考我以前发表的相关文章
下面这个例子从多个角度来找到虚函数的指针,并对其进行调用
方法一:定义一个对象找到对象中存放的虚函数所在表的头指针,并将其第一个指针作为我们调用的函数指针
方法二:直接通过二级指针找到函数指针
#include<stdio.h>
#include <iostream> //cout hex ……
#include <iomanip> //setw
using namespace std;
#define PRINT_SIZE(CLASS_NAME) /
cout << "The size of " << #CLASS_NAME << " is " << sizeof(CLASS_NAME) << endl;
#define PRINT_DETAIL(CLASS_NAME, OBJECT_NAME) /
cout << "The detail of " << #CLASS_NAME << " is "; /
for (int i = 0; i < sizeof(OBJECT_NAME); ++i) { /
cout.fill('0'); /
cout << setw(2) << hex << ((short)((char*)(&(OBJECT_NAME)))[i] & 0x00ff); /
cout << ' '; } /
cout << setw(0) << dec << endl;
#define PRINT_SIZE_DETAIL(CLASS_NAME) /
PRINT_SIZE(CLASS_NAME) /
CLASS_NAME _##CLASS_NAME; /
PRINT_DETAIL(CLASS_NAME, _##CLASS_NAME)
class A
{
public:
virtual int Calc2(int a);
//int Calc2(int a);
};
int A::Calc2(int a)
{
return 1;
}
int main( )
{
int ret = 0;
A *Ao = new A() ;
unsigned long *pul;
unsigned long **ppul;
A a;
PRINT_SIZE_DETAIL(A);
//ret = Ao->Calc2(0xFFFF);
//pul = (unsigned long *)0x00444c80;
pul = (unsigned long *)(&a);
ppul = (unsigned long **)(&a);
printf("ret=%08X/n",**ppul);
for(ret =0;ret<4;ret++)
{
cout.fill('0');
cout << setw(2) << hex << ((short)((char*)(pul))[ret] & 0x00ff);
cout << ' ';
}
int (*p)(int);
//p = (int (*)(int))0x00401150;
p = (int (*)(int))**ppul;
ret = (*p)(1);
printf("ret=%d/n",ret);
ret = Ao->Calc2(0xFFFF);
printf("ret=%d/n",ret);
return 0;
}