How to call rust library in c


#1

How i call rust functions in c language and vice versa . will you explain with simple example. PLEASE.


#2

To call Rust from C:

#[no_mangle]
extern "C" fn foo() {
    // stuff
}

To call C from Rust:

extern "C" {
    fn foo();
}

fn bar() {
    foo();
}

#3

There’s an explanation with examples in this blog post: https://blog.rust-lang.org/2015/04/24/Rust-Once-Run-Everywhere.html


#4

Take a look at the ffi-omnibus. It has examples for both C and other languages


#5

You can’t just use pub extern "C" to call a function from Rust :frowning:

Visibility and exporting of functions in inconsistent in Rust. It is done differently depending on whether Rust or C will call them.

For C both visibility and exporting are done with the #[no_mangle] attribute instead of pub and accessibility from the crate root.