c++crust

Using C/C++ enumeration from .h in Rust


The Cargo project requires using an enumeration from a large C header file. There are at least 1000 different variants of this enumeration.

Here is an example of what the header looks like:

#ifndef MY_ENUMS_H
#define MY_ENUMS_H

enum Status {
   OK = 0,
   OUR_BASE = OK,
   CONNECTION_ERROR = OUR_BASE + 1,
   OPEN_FAILED = OUR_BASE + 2,
   ...
};

#endif // MY_ENUMS_H

I'd like to re-use these in Rust. Is there a way to do this? I've looked into bindgen, but it looks like it compiles, whereas this is header only.


Solution

  • I ended up using bindgen to accomplish this.

    build.rs file:

    fn main() {
        let bindings = bindgen::builder().header("./src/include/enum.h").generate().expect("Unable to generate bindings");
        bindings.write_to_file("./src/enum.rs").expect("Couldn't write bindings");
    }
    

    src/main.rs file example:

       include!("enum.rs");
       fn main() {
          let status: Status = Status_CONNECTION_ERROR;
       }