开发者

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";

Now i need to call do_fork() just by *pFunc. So is that possible ?

Either C/C++ code is welcomed , many thanks !


Neither C nor C++ have enough reflection to do this out of the box, so you will have to implement your own scheme.

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)();

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.


Not entirely sure if it's what you're looking for but you could easily use dlopen and dlsym.

void *dlsym(void *restrict handle, const char *restrict name);

The dlsym() function shall obtain the address of a symbol defined within an object made accessible through a dlopen() call. The handle argument is the value returned from a call to dlopen() (and which has not since been released via a call to dlclose()), and name is the symbol's name as a character string.

That said, it usually doesn't come to this in C so you likely don't actually need it.


It is indeed possible, but it's not entirely easy.

What you need to do is to compile your binary for dynamic binding; and then getting the function with dlsym, as per @cnicutar's answer.

There are caveats, of course; but if the function in question is in a dynamically linked library with a path guaranteed to be known at runtime (a plug-in or extension module would match this), it's a fairly safe way of doing things.

dlsym-ing function in the active executable, OTOH, gets hairy.


If it must be done using the name of the function and you don't want to go about cnicutar's way, you could go with this method:

Compile each function in its own *.exe file. Use system(PATH_TO_FUNCTION_EXECUTABLE/FUNCTION_NAME) to call the executable.


If you know all the functions you'll need to call, and they're placed in one program, you can use this:

void do_fork()
{
    printf ("Fork called.\n");
}

void callFunc(char *funcName)
{
    if (strcmp(funcName, "do_fork") == 0) do_fork();
}

int main()
{
    char *pFunc = "do_fork";
    callFunc(pFunc);
    return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜