How to Use the cxx Crate for Rust/C++ Interop
The cxx crate is not used for building the Rust compiler itself; it is a library for safe Rust/C++ interoperability in application code. To use cxx in your project, add the dependency to your Cargo.toml and define your C++ bindings in a #[cxx::bridge] module.
[dependencies]
cxx = "1.0"
#[cxx::bridge]
mod ffi {
extern "Rust" {
fn rust_function() -> i32;
}
unsafe extern "C++" {
type CppType;
fn cpp_function() -> i32;
}
}
fn rust_function() -> i32 {
42
}
fn main() {
let result = rust_function();
println!("Rust result: {}", result);
}
You must also provide the corresponding C++ implementation file (e.g., ffi.cpp) and ensure your build script (build.rs) invokes cxx_build::bridge!() to generate the glue code.