Call function by name like Node.js global["funcname"]()


Is it possible to call a function by its name as string ?
Something like global["funcname"]() in Node.js

Thank you in advance for your help.

No. You can create a constant hash map or array of function pointers and call things you explicitly put in the collection.


Why do you want to do this?

I want to do a kind of plugins system and I don't want the plugin to have to register the functions

How are you loading the plugins? If it's dynamically (like through libloading,) you'd have to use strings to find the functions in the plugins anyway, so you'd do something like

let func: libloading::Symbol<unsafe extern fn()> = plugin.get("funcname")?;

Disclaimer: don't do this without completely understanding why you need to do it this way, and all of the reasons why you shouldn't do it this way.

mod one_place {
    extern "C" fn callee() {
        catch_unwind(|| { println!("callee") });
mod other_place {
    extern "C" {
        fn callee();
    fn main() {
        unsafe { callee(); }

Some of the big reasons to not do this:

  • names must be unique in the entire linked binary.
  • absolutely no type safety.
  • only FFI-safe (#[repr(C)]) types.
  • panicking across the border is strictly undefined behavior.

Rather, you probably want something like a proc macro that annotates the function to register the function, complete with type safety. This can be done at link time rather than run time using linkme, load time using inventory, or similar. (Linkme is probably the least bad.)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.