How to call function c from the name stored in char * pointer?

I wanted to dynamically call a function by its name, for example, suppose it has the following function and line:

void do_fork() { printf ("Fork called.\n"); } char *pFunc = "do_fork"; 

Now I need to call do_fork() only *pFunc . So maybe?

Any C / C ++ code is welcome, thank you very much!

+6
source share
5 answers

Neither C nor C ++ has enough reflection to make it out of the box, so you have to implement your own scheme.

In C ++, a more or less canonical way to do this is to use a string map to indicate pointers. Something like that:

 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 restriction can be somewhat removed (to cover reasonably compatible signatures) using std::function and std::bind instead of a simple function pointer.

+14
source

Not quite sure if this is what you are looking for, but you can easily use dlopen and dlsym .

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

The dlsym () function should get the address of the character defined in the object, accessible via dlopen (). The handle argument is the value returned from dlopen () (and has since been issued through a call to dlclose ()) and name is the name of the character as a character string.

However, in C this usually fails, so you really don't need it.

+4
source

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

What you need to do is compile your binary for dynamic linking; and then get the function with dlsym as @cnicutar answer.

Of course, there are reservations; but if the function in question is in a dynamically linked library with a circuit, which, as you know, will be known at runtime (the plug-in module or extension module will correspond to this), this is a pretty safe way to do something.

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

+1
source

If you need to do this using the function name, and you do not want to follow the cnicutar path, you can go with this method:

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

0
source

If you know all the functions that you need to call, and they are 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
source

Source: https://habr.com/ru/post/891527/


All Articles