如何从存储在char *指针中的name调用c函数? [英] How to call a c function from name , which is stored in a char* pointer?
问题描述
我想按名称动态调用一个函数,例如,假设具有以下函数和字符串:
I wanted to dynamically call a function by its name , e.g , suppose have the following function and string:
void do_fork()
{
printf ("Fork called.\n");
}
char *pFunc = "do_fork";
现在我只需要通过 * pFunc
来调用 do_fork()
.那有可能吗?
Now i need to call do_fork()
just by *pFunc
. So is that possible ?
欢迎使用C/C ++代码,非常感谢!
Either C/C++ code is welcomed , many thanks !
推荐答案
C和C ++都没有足够的反射来实现此功能,因此您将必须实现自己的方案.
Neither C nor C++ have enough reflection to do this out of the box, so you will have to implement your own scheme.
在C ++中,或多或少的规范方法是使用字符串映射到函数指针.像这样:
In C++, the more or less canonical way to do that is using a map of strings to function pointers. Something like this:
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
和 std :: bind
而不是普通的函数指针,可以稍微解除此限制(以包含合理兼容的签名).
Of course, this is limited to functions with exactly the same signature. However, this limitation can be somewhat lifted (to encompass reasonably compatible signatures) by using std::function
and std::bind
instead of a plain function pointer.
这篇关于如何从存储在char *指针中的name调用c函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!