The
build.rs
file’s main function is a build script that configures the Rust compiler to link against the dynamic library by telling cargo through standard output (print).- dynamic library path:
cargo:rustc-link-search=native=$PATH
- dynamic library name:
cargo:rustc-link-lib=dylib=$NAME
Bindgen
- library path
- wrapper header path
- output binding rust file
let bindings = bindgen::Builder::default() // The input header we would like to generate // bindings for. .header("wrapper.h") .clang_arg("-v") .derive_debug(true) .derive_default(true) // included header files changed. .parse_callbacks(Box::new(bindgen::CargoCallbacks::new())) // Finish the builder and generate the bindings. .generate() // Unwrap the Result and panic on failure. .expect("Unable to generate bindings"); // Write the bindings to the $OUT_DIR/bindings.rs file. let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); bindings .write_to_file(out_path.join("bindings.rs")) .expect("Couldn't write bindings!");
build.rs binding in lib.rs
lib.rs
file can include the generated bindings and allows the Rust code to interact with the C functions.
- The
#![allow(...)]
attributes are used to suppress warnings about naming conventions.
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
: This line includes the generated bindings file, which is created by bindgen during the build process.
Source code usage
- The
extern "C"
block declares theimage_classifier
function from the Darknet library, making it available for use in Rust.
- This function can be called from the Rust code as if it were a normal Rust function.