Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a Rust function in C?

The first "similar question" shown to me while posting this is called "How to call C function in Rust". This is the opposite of what I need. Every tutorial I can find that technically does answer my question, only does so by exporting the Rust function in a DLL so a C executable can call it, using extern "C".

But I have a Rust executable that is calling a C DLL function that takes a Rust function pointer as a parameter (I haven't actually written this C function yet). Any basic examples demonstrating how to do this? I've already got Rust calling some of the C DLL functions, but I need to write code for both Rust and C so that C can execute a Rust callback.

like image 452
GirkovArpa Avatar asked Aug 31 '25 20:08

GirkovArpa


1 Answers

If you have this C code compiled to a library named lib.dll, exporting a single function which accepts a pointer to a function which takes no arguments and returns nothing:

__declspec(dllexport) void foo(void (*callback)()) {
    callback();
}

Then this Rust code will send the function callback to that C function. Upon execution, it prints the line "callback()":

extern "C" fn callback() -> () {
    println!("callback()");
}

fn main() {
    println!("main()");
    call_dynamic();
}

fn call_dynamic() -> Result<u32, Box<dyn std::error::Error>> {
    unsafe {
        let lib = libloading::Library::new("lib.dll")?;
        let foo: libloading::Symbol<extern "C" fn(extern "C" fn()) -> u32> = lib.get(b"foo")?;
        Ok(foo(callback))
    }
}

You should see this in your console:

main()
callback()

I am on Windows and compiled the C code with this command:

gcc --shared lib.c -o lib.dll

The Rust code was run with this:

cargo run
like image 58
GirkovArpa Avatar answered Sep 03 '25 10:09

GirkovArpa