Use the bindgen crate to automatically generate safe Rust bindings for your C library headers. Run bindgen on your header file to create a Rust module, then wrap the generated functions in safe Rust functions that handle error checking and memory management.
// Add to Cargo.toml: bindgen = "0.69"
// Run: bindgen path/to/header.h -o src/bindings.rs
mod bindings {
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
}
pub fn safe_call() -> Result<i32, String> {
let result = unsafe { bindings::c_function() };
if result < 0 {
Err("C function failed".to_string())
} else {
Ok(result)
}
}