GirkovArpa / call-rust-in-c

Simple demo example of how to pass a Rust function to be executed by a C library (.dll).

Home Page:https://stackoverflow.com/questions/66288855/how-to-call-a-rust-function-in-c

Repository from Github https://github.comGirkovArpa/call-rust-in-cRepository from Github https://github.comGirkovArpa/call-rust-in-c

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

About

Simple demo example of how to pass a Rust function to be executed by a C library (.dll).

https://stackoverflow.com/questions/66288855/how-to-call-a-rust-function-in-c

License:MIT License


Languages

Language:Rust 84.9%Language:C 15.1%