Search code examples
rustdylib

Call external function in dylib


I have main application with code that looks like this:

pub fn load_lib() {
    let dylib = libloading::Library::new("example.dylib") ...
    unsafe { *dylib.get(b"fn_in_dylib") } ...
    // calling function from dylib.
}
pub extern "Rust" fn fn_in_main_app() { ... } // Function that I want to call from dylib

example.dylib dyliib is loaded successfully and function from dylib is called without any problems.

But here is what I'm trying to do inside dylib:

pub extern "Rust" fn fn_in_dylib() {
    fn_in_main_app(); // Here I'm trying to call function defined in main application.
}
extern "Rust" {
    fn fn_in_main_app();
}

But this doesn't even compile:

Undefined symbols for architecture x86_64:
    "_fn_in_main_app", referenced from:

I'm not sure that I'm using the correct way to implement this, so it didn't surprise me when it didn't compile. But I hope it shows what I'm actually trying to.


Solution

  • Dylibs can't depend on the application that loads them. The dylib dependency graph must be entirely linear, circular depedencies are not allowed. Depending on what you're doing it may be possible to move fn_in_main_app to an upstream dependency of the dylib. You could also pass in a function pointer to the dylib:

    pub extern "Rust" fn fn_in_dylib(fn_in_main_app: fn()) {
        (fn_in_main_app)();
    }