Search code examples
c++structfunction-pointers

Invoking method inside of an unknown struct in c++


Lets say a user creates their own struct that contains some code:

struct NormalShader
{
    vec3 normal;
    vec3 color;

    void main()
    {
        color = normal * 127.5f + 127.f;
    }
};

Then the main piece of code runs and tries to simulate this struct:

void ShaderRun()
{
    void* structData = alloca(structSize);
    LoadAttributes(structData);

    Invokemain(structData); //<- Pseudocode here that executes main() with the structs data at the 'structData' pointer
}

So my question is: Is it possible to manually initialize an unknown struct, and then somehow hack its member function for it to work on its own data, without directly having access to said struct.

EDIT: To clarify: By hack, I mean to force the main function inside NormalShader to think its struct elements are structData and to execute its code on these elements.


Solution

  • Make Invokemain() take a template parameter that the caller can use to specify the structure type being passed in, eg:

    template <typename T>
    void Invokemain(T &data)
    {
        data.main();
    }
    

    Then the caller can allocate whatever struct it needs to, eg:

    struct NormalShader
    {
        vec3 normal;
        vec3 color;
    
        void main()
        {
            color = normal * 127.5f + 127.f;
        }
    };
    
    void ShaderRun()
    {
        NormalShader data;
        ...
        Invokemain(data);
    }