我想通过名称动态调用函数,例如,假设有以下函数和字符串:
void do_fork()
{
printf ("Fork called.\n");
}
char *pFunc = "do_fork";
Run Code Online (Sandbox Code Playgroud)
现在,我要打电话do_fork()只是*pFunc.那可能吗?
欢迎使用C/C++代码,非常感谢!
sbi*_*sbi 14
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)();
Run Code Online (Sandbox Code Playgroud)
当然,这仅限于具有完全相同签名的功能.然而,通过使用std::function和std::bind代替普通函数指针,可以在一定程度上解除这种限制(以包含合理兼容的签名).