2 releases
new 0.1.4 | Dec 10, 2024 |
---|---|
0.1.3 | Dec 7, 2024 |
#1481 in Rust patterns
198 downloads per month
Used in seesaw-cli
94KB
333 lines
Generate traits from C header files.
When rewriting a C libary in Rust, you often want to preserve the original C header files.
This is possible using this crate in conjuction with bindgen
.
Take the following C
header.
typedef struct yakshaver yakshaver;
/** create a yakshaver */
yakshaver *create(void);
/** destroy a yakshaver */
void destroy(yakshaver *);
/** get number of yaks shaved */
unsigned int yaks_shaved(const yakshaver *);
/** shave some yaks */
int shave(yakshaver *);
In your build.rs
script:
// build.rs
fn main() -> Result<(), Box<dyn std::error::Error>> {
let bindings = bindgen::builder().header("yakshaver.h").generate()?;
seesaw::seesaw("Yakshaver", &bindings, "generated/seesaw.rs")?;
bindings.write_to_file("generated/bindgen.rs")?;
Ok(())
}
The generated file will look like this:
/* this file is @generated by seesaw */
#[allow(unused)]
trait Yakshaver {
#[doc = " create a yakshaver"]
unsafe extern "C" fn create() -> *mut yakshaver;
#[doc = " destroy a yakshaver"]
unsafe extern "C" fn destroy(arg1: *mut yakshaver);
#[doc = " get number of yaks shaved"]
unsafe extern "C" fn yaks_shaved(arg1: *const yakshaver) -> ::std::os::raw::c_uint;
#[doc = " shave some yaks"]
unsafe extern "C" fn shave(arg1: *mut yakshaver) -> ::std::os::raw::c_int;
}
And you can export the same ABI as the C library using no_mangle
,
which simply adds #[no_mangle]
to each of the functions.
#[seesaw::no_mangle]
impl YakShaver for () { .. }
Dependencies
~0–720KB
~14K SLoC