Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I export a function written in Rust to C code?

Tags:

rust

ffi

bindgen

I'm venturing for the first time with Rust's FFI system and bindgen. So far it's going better than I expected but I have now hit a roadblock.

My setup is the following: I have a library written in C that I can compile and that exposes some function declarations for the user to define. So let's assume one header has the following declaration:

extern void ErrorHandler(StatusType Error);

With bindgen, I now get this function also "declared" (?) in bindings.rs:

extern "C" {
    pub fn ErrorHandler(Error: StatusType);
}

How can I now define the function in my Rust code?

I tried:

#[no_mangle]
pub extern "C" fn ErrorHandler(Error: StatusType) {
  /* do something */
}

However now I get the following error that tells me the function is defined twice:

4585 |     pub fn ErrorHandler(Error: StatusType);
     |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `ErrorHandler` redefined here
     |
    ::: src\main.rs:7:1
     |
7    | pub extern "C" fn ErrorHandler(Error: StatusType) {
     | ---------------------------------------------- previous definition of the value `ErrorHandler` here
     |
     = note: `ErrorHandler` must be defined only once in the value namespace of this module

Thank you for your help!

like image 295
pedro Avatar asked Sep 16 '25 08:09

pedro


1 Answers

The problem is coming from the forward declaration from bindgen. Rust unlike C and C++ does not have forward declaration. So remove this:

extern "C" {
    pub fn ErrorHandler(Error: StatusType);
}

and keep this:

#[no_mangle]
pub extern "C" fn ErrorHandler(Error: StatusType) {
  /* do something */
}
like image 157
dev65 Avatar answered Sep 17 '25 22:09

dev65



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!