Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call C function in Rust

Tags:

rust

I'm a C programmer and I'm trying to call Rust function in my application and the rust function also need call C functions which exist at my application.

I know that if I want call C function in Rust I have to do like this

#[link(name = "mylib")]
extern "C" {
    pub fn c_function();
}

But the c_function doesn't exist in any lib but only in my application env now.

For example: My C code is

void c_function()
{
    return 1;
}

void main()
{
    rust_function();
}

My Rust code is(cargo new --lib myrustlib)

pub unsafe extern "C" fn  rust_function() {
    //If I want to call c_function which is in C world here, How could I do this?
    //I have tried using extern "C" {pub fn c_function();} but faild.  
    //And an error is outputted like this "undefined reference to `c_function'"
}

like image 299
Nail Jay Avatar asked Jul 26 '26 13:07

Nail Jay


1 Answers

You're on the right track. You can auto-generate C header from the Rust program with cbindgen, and the other way, Rust bindings with bindgen.

Add crate-type = ["lib", "staticlib", "cdylib"] to Cargo.toml to generate .a and .so/.dylib/.dll versions of the Rust library that you can link with the C program.

like image 133
Kornel Avatar answered Jul 28 '26 06:07

Kornel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!