我想通过函数的名称动态调用函数,例如,假设有以下函数和字符串:
void do_fork()
{
printf ("Fork called.\n");
}
char *pFunc = "do_fork";
现在我需要打电话do_fork()
就在*pFunc
。那么这可能吗?
欢迎 C/C++ 代码,非常感谢!
C 和 C++ 都没有足够的反射来开箱即用地执行此操作,因此您必须实现自己的方案。
在 C++ 中,或多或少规范的方法是使用字符串到函数指针的映射。像这样的事情:
typedef void (*func_t)();
typedef std::map<std::string,func_t> func_map_t;
// fill the map
func_map_t func_map;
func_map["do_fork"] = &do_fork;
func_map["frgl"] = &frgl;
// search a function in the map
func_map_t::const_iterator it = func_map.find("do_fork");
if( it == func_map.end() ) throw "You need error handling here!"
(*it->second)();
当然,这仅限于具有完全相同签名的函数。但是,可以通过使用来稍微解除此限制(以包含合理兼容的签名)std::function
and std::bind
而不是普通的函数指针。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)