Skip to content

Instantly share code, notes, and snippets.

@lexuanquynh
Created December 21, 2022 00:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lexuanquynh/b3e38cd3117f34167a3768b44eeda810 to your computer and use it in GitHub Desktop.
Save lexuanquynh/b3e38cd3117f34167a3768b44eeda810 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
class Sample1 {
public:
virtual void vMethod1() {
printf("This is virtual method 1\n");
printf("member1 = %d\n", member1);
}
virtual void vMethod2() {
printf("This is virtual method 2\n");
}
void method2() {
printf("This is NONVIRTUAL method 2\n");
}
public:
int member1;
int member2;
};
//Define method type
//Thêm tham số thisPtr ở đây
typedef void (*MyFunc)(Sample1 *thisPtr);
struct ClassDesc {
MyFunc* vmt;
int member1;
int member2;
};
void fakeVMethod1(ClassDesc* thisPtr) {
printf("fake virtual method1 - member1: %d\n", thisPtr->member1);
}
void fakeVMethod2(ClassDesc* thisPtr) {
printf("fake virtual method2 - member2: %d\n", thisPtr->member2);
}
void constructor(ClassDesc* desc) {
//Init virtual method table
desc->vmt = new MyFunc[2];
desc->vmt[0] = (MyFunc)&fakeVMethod1;
desc->vmt[1] = (MyFunc)&fakeVMethod2;
}
void destructor(ClassDesc* desc) {
//delete virtual method table
delete []desc->vmt;
}
int main(int argc, const char * argv[]) {
Sample1 *a = new Sample1();
a->member1 = 1000;
printf("size of Sample1: %d\n", sizeof(Sample1));
MyFunc *virtualMethodTable = (MyFunc*)(*(MyFunc*)a);
virtualMethodTable[0](a); //call method1
virtualMethodTable[1](a); //call method2
printf("\n--------------FAKE CLASS----------------\n\n");
ClassDesc* clsDesc = new ClassDesc(); // |
constructor(clsDesc); // | <=> a = new Sample1();
clsDesc->member1 = 2000;
clsDesc->member2 = 3000;
Sample1* b = reinterpret_cast<Sample1*>(clsDesc); // cast Class Description struct to Sample1*
b->vMethod1();
b->vMethod2();
destructor(clsDesc); //
delete clsDesc; // <=> delete b;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment