3

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'"
}

Nail Jay
  • 267
  • 3
  • 9
  • Do you want to link at it during compile time or runtime, e.g. via `dlopen`? – hellow Aug 05 '19 at 06:45
  • I found one resource which will help you. https://blog.jfo.click/calling-a-c-function-from-rust/ so, please read it and try to solve on your way. – MK Patel Aug 05 '19 at 06:47
  • It's even explained in the [rust book](https://rust-embedded.github.io/book/interoperability/c-with-rust.html). `'m trying to call Rust function in my application and the rust function also need call C functions` - do you want to call a C code from rust or rust code from C? – KamilCuk Aug 05 '19 at 06:53
  • Possible duplicate of [Can I call C or C++ functions from Rust code?](https://stackoverflow.com/questions/24105186/can-i-call-c-or-c-functions-from-rust-code) – Stargateur Aug 05 '19 at 07:22
  • to be able to call symbol in a lib from main exe you need special flag, and this is a very strange thing to do. – Stargateur Aug 05 '19 at 07:24

1 Answers1

2

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.

WhyNotHugo
  • 9,423
  • 6
  • 62
  • 70
Kornel
  • 97,764
  • 37
  • 219
  • 309