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 !
The call by pointer method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument.
Function pointers can be stored in variables, structs, unions, and arrays and passed to and from functions just like any other pointer type. They can also be called: a variable of type function pointer can be used in place of a function name.
The name of a function is not a pointer. What you're seeing is a result of how expressions work in C. p = addition; the name of the function is implicitly converted to a pointer.
Function pointers in C can be used to create function calls to which they point. This allows programmers to pass them to functions as arguments. Such functions passed as an argument to other functions are also called callback functions.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With