OK, so that's what I need :
func
with some value, given by the user (not a constant)func
?UPDATE:
Perhaps thought that what I needed was pretty self-explanatory, but since I'm noticing many downvotes, here you are :
string func = "myfunc";
I need something like call(func)
, which will call myfunc
. Like PHP's call_user_func_array()
Any ideas?
I had a look at mixins but this doesn't look like what I'd need.
P.S. I'm tagging the question with c
and c++
too, since a universal solution could be theoretically possible, given the similarities among the languages.
Programming languages generally do not provide a way to access function names during runtime, as those names are usually stripped out by the linker, leaving behind only machine code.
As user3286380 suggested, one way to tackle this problem, which would work in all languages, is to make a table which cross-references function names and pointers to the respective functions. Then, your program can look up this table during run time.
If the language in question allows introspection (either run-time or compile-time), you can enumerate the functions in your module or program, and find the function whose name the user entered. In D, you can do this by using the allMembers
trait on a module. This will give you an array of all declarations in the module; the next step would be to filter out functions, check that the function signature matches, then generate a switch statement which calls the respective function. You can use CTFE and string mixins to achieve the above.
Create an array of pairs with the first element of each pair being the string function name and the second being the pointer to the function. Search the array and when the name is found, call it using the pointer. Note that Python has a dictionary class that enables you to do this as key:value pairs.
I see 3 ways of doing that:
If you know in advance a collection of functions from which to choose, you could register an associative table of string
-> functor
where functor records both the function address and signature, something like std::function
in C++
Otherwise, a more complex solution is to inspect the debug symbols of your own executable and build your table from that. You could also use pre-processors (like Qt's MOC) to build this table, or in the case of D use the builtin compile-time reflexivity.
If you really need flexibility use an interpreter instead of a compiler. Cling is a nice LLVM based C++ interpreter with just-in-time compilation.
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