64,676
社区成员
发帖
与我相关
我的任务
分享
//用C来实现C++虚表机制
//理论可以用函数指针和结构体的语言都可以实现
//-------------------------------C++的对象构建,确定虚表结构-------------------------------
class IDispath
{
public:
virtual void __stdcall Find() = 0;
virtual void __stdcall Invoke(int x) = 0;
};
class ITest :public IDispath
{
public:
virtual void __stdcall Use() = 0;
};
class CTest :public ITest
{
public:
void __stdcall Find()
{
printf("Find\n");
};
void __stdcall Invoke(int x)
{
printf("Invoke(%d)\n",x);
};
void __stdcall Use()
{
printf("use\n");
};
};
//-------------------------------C 部分构造和C++对象相同的虚表结构-------------------------------
typedef struct STest STest;
struct vtpr//虚表内容
{
void (__stdcall *Find)( STest* This);//虚表所对应的函数指针 第一个参数为对象的this指针
void (__stdcall *Invoke)( STest* This,int x);
void (__stdcall *Use)( STest* This);
};
struct STest
{
struct vtpr * p;//虚表指针
};
int main(int argc, char* argv[])
{
CTest* t =new CTest;
//利用C构建的虚表进行函数调用
STest* pTest = (STest*)t;
pTest->p->Find(pTest);
pTest->p->Invoke(pTest,23);
pTest->p->Use(pTest);
delete t;
return 0;
}