rustffibindgen

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


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!


Solution

  • 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 */
    }