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.

Revisions

  1. Daethalus created this gist Apr 15, 2024.
    47 changes: 47 additions & 0 deletions virtual.cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    #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;
    }