问题描述
假设用户创建了自己的包含一些代码的结构:
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);
}