Skip to content

GirkovArpa/call-rust-in-c

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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()