Skip to content

Instantly share code, notes, and snippets.

@Daethalus
Created April 15, 2024 16:48
Show Gist options
  • Save Daethalus/a0a109daf097745d1b031b13a9b92842 to your computer and use it in GitHub Desktop.
Save Daethalus/a0a109daf097745d1b031b13a9b92842 to your computer and use it in GitHub Desktop.
virtual table runtime implementation
#include <iostream>
struct MyInterface
{
virtual void UpdateValue(int vl) = 0;
virtual int CallTwo(int a) = 0;
};
struct Data
{
int value{};
};
struct InterfaceMemory
{
size_t* vtable = nullptr;
Data data{};
};
void FuncCall(InterfaceMemory* memory, int vl)
{
memory->data.value = vl;
}
int FuncTwo(InterfaceMemory* memory, int a)
{
return memory->data.value + a;
}
int main()
{
InterfaceMemory memory{};
memory.vtable = (size_t*)malloc(sizeof(size_t) * 2);
memory.vtable[0] = (size_t)FuncCall;
memory.vtable[1] = (size_t)FuncTwo;
MyInterface* interface = reinterpret_cast<MyInterface*>(&memory);
interface->UpdateValue(20);
int res = interface->CallTwo(30);
std::cout << "res " << res << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment