简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM