在C ++中的未知结构内部调用方法

问题描述

假设用户创建了自己的包含一些代码的结构:

struct NormalShader
{
    vec3 normal;
    vec3 color;

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

然后运行主要代码,并尝试模拟此结构:

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

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

所以我的问题是:是否可以手动初始化一个未知的结构,然后以某种方式破解其成员函数,使其在不直接访问该结构的情况下就可以处理自己的数据。

编辑: 需要说明的是:hack是指迫使main内的NormalShader函数认为其struct元素是structData并在这些元素上执行代码。

解决方法

使Invokemain()带有一个模板参数,调用者可以使用它来指定要传递的结构类型,例如:

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

然后,调用方可以分配所需的任何结构,例如:

struct NormalShader
{
    vec3 normal;
    vec3 color;

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

void ShaderRun()
{
    NormalShader data;
    ...
    Invokemain(data);
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...