Skip to content

Latest commit

 

History

History
45 lines (39 loc) · 827 Bytes

README.md

File metadata and controls

45 lines (39 loc) · 827 Bytes

Call Rust In C

Simple demo of sending Rust function pointer to C library, which executes it.

Instructions

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

Compile the above C code to a dynamic link library with:

gcc --shared lib.c -o lib.dll
extern crate libloading;
extern crate libc;

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<fn(fn()) -> u32> = lib.get(b"foo")?;
        Ok(foo(callback))
    }
}

Compile and run the above Rust code with:

cargo run

You should see this in your console:

main()
callback()