### Configure build.rs for autocxx Source: https://google.github.io/autocxx/tutorial.html Set up your build.rs file to specify the C++ include path and compile your C++ code using autocxx_build. This example assumes C++ bindings are in main.rs and uses C++14. ```rust fn main() -> miette::Result<()> { let include_path = std::path::PathBuf::from("src"); // This assumes all your C++ bindings are in main.rs let mut b = autocxx_build::Builder::new("src/main.rs", &[&include_path]).build()?; b.flag_if_supported("-std=c++14") .compile("autocxx-demo"); // arbitrary library name, pick anything println!("cargo:rerun-if-changed=src/main.rs"); // Add instructions to link to any C++ libraries you need. Ok(()) } ``` -------------------------------- ### Define C++ constant Source: https://google.github.io/autocxx/other_features.html Example of a C++ preprocessor definition. ```cpp #define BOB "Hello" ``` -------------------------------- ### Integrating Manual cxx::bridge with autocxx Source: https://google.github.io/autocxx/print.html Combine automatically generated bindings with manually crafted `cxx::bridge` modules. This example shows how a manual `ffi2` module can refer to types generated by `autocxx` in `ffi`. ```rust autocxx::include_cpp! { #include "foo.h" safety!(unsafe_ffi) generate!("take_A") generate!("A") } #[cxx::bridge] mod ffi2 { unsafe extern "C++" { include!("foo.h"); type A = crate::ffi::A; fn give_A() -> UniquePtr; // in practice, autocxx could happily do this } } fn main() { let a = ffi2::give_A(); assert_eq!(ffi::take_A(&a), autocxx::c_int(5)); } ``` -------------------------------- ### Define C++ Template and Struct Source: https://google.github.io/autocxx/cpp_types.html A C++ header example defining a template struct and a function to prepare and consume it. ```cpp #include struct Tapioca { std::string yuck; }; template struct Tea { Tea() : floaters(nullptr) {} Floaters* floaters; }; inline Tea prepare() { Tea mixture; // prepare... return mixture; } inline void drink(const Tea&) {} ``` -------------------------------- ### Rust Bindings for C++ Modules with autocxx Source: https://google.github.io/autocxx/large_codebase.html Generates Rust bindings for C++ code using autocxx. This example shows how to define separate modules for base types and dependent functions, using `extern_cpp_type!` to link them. ```rust use autocxx::prelude::*; pub mod base { autocxx::include_cpp! { #include "input.h" name!(ffi2) safety!(unsafe_ffi) generate!("A") generate!("B") } pub use ffi2::*; } pub mod dependent { autocxx::include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("handle_a") generate!("create_a") extern_cpp_type!("A", crate::base::A) extern_cpp_type!("B", super::super::base::B) pod!("B") } pub use ffi::*; } fn main() { let a = dependent::create_a(base::B::VARIANT).within_unique_ptr(); dependent::handle_a(&a); } ``` -------------------------------- ### Define C++ struct A Source: https://google.github.io/autocxx/print.html Defines a simple C++ struct `A` with a constructor, `set`, and `get` methods, and a public member `a`. This is a POD type. ```cpp #include #include struct A { A() {} void set(uint32_t val); uint32_t get() const; uint32_t a; }; ``` -------------------------------- ### Passing Raw Pointers to C++ Functions Source: https://google.github.io/autocxx/references_etc.html When passing a raw pointer to a C++ function from Rust, `unsafe` is required. This example demonstrates how to obtain a raw pointer from a `cxx::UniquePtr` and pass it, ensuring proper pinning and unchecked conversion. ```rust let mut a = ffi::A::make_unique(); unsafe { ffi::TakePointerToA(std::pin::Pin::<&mut ffi::A>::into_inner_unchecked(a.pin_mut())) }; ``` -------------------------------- ### Generate Diagnostic Build Logs Source: https://google.github.io/autocxx/reporting_bugs.html Capture detailed build logs including C++ bindings for troubleshooting when minimization is not possible. ```bash cargo clean -p && RUST_LOG=autocxx_engine=info cargo build -vvv ``` -------------------------------- ### Define the build script for autocxx Source: https://google.github.io/autocxx/print.html Create a build.rs file to configure the autocxx builder and specify include paths. ```rust fn main() -> miette::Result<()> { let include_path = std::path::PathBuf::from("src"); // This assumes all your C++ bindings are in main.rs let mut b = autocxx_build::Builder::new("src/main.rs", &[&include_path]).build()?; b.flag_if_supported("-std=c++14") .compile("autocxx-demo"); // arbitrary library name, pick anything println!("cargo:rerun-if-changed=src/main.rs"); // Add instructions to link to any C++ libraries you need. Ok(()) } ``` -------------------------------- ### Construct and use C++ object A in Rust Source: https://google.github.io/autocxx/print.html Demonstrates constructing a C++ object `A` on the stack using `moveit!`, and on the heap using `within_unique_ptr()` and `within_box()`. It also shows how to call methods on these objects. ```rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("A") } fn main() { moveit! { let mut stack_obj = ffi::A::new(); } stack_obj.as_mut().set(42); assert_eq!(stack_obj.get(), 42); let mut heap_obj = ffi::A::new().within_unique_ptr(); heap_obj.pin_mut().set(42); assert_eq!(heap_obj.get(), 42); let mut another_heap_obj = ffi::A::new().within_box(); another_heap_obj.as_mut().set(42); assert_eq!(another_heap_obj.get(), 42); } ``` -------------------------------- ### C++ function declaration for reference passing Source: https://google.github.io/autocxx/safety.html Declares a C++ function `print_thing` that takes a constant reference to a `Thing` struct. This example illustrates the promises autocxx makes about how such references are handled. ```cpp struct Thing; void print_thing(const Thing& thing); ``` -------------------------------- ### Run Integration Tests Source: https://google.github.io/autocxx/contributing.html Execute tests within the integration-tests directory to verify build stability after dependency changes. ```bash cd integration-tests; cargo test ``` -------------------------------- ### Construct and use C++ objects in Rust Source: https://google.github.io/autocxx/cpp_types.html Demonstrates creating non-POD C++ objects on the stack, C++ heap, and Rust heap using autocxx and moveit. ```rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("A") } fn main() { moveit! { let mut stack_obj = ffi::A::new(); } stack_obj.as_mut().set(42); assert_eq!(stack_obj.get(), 42); let mut heap_obj = ffi::A::new().within_unique_ptr(); heap_obj.pin_mut().set(42); assert_eq!(heap_obj.get(), 42); let mut another_heap_obj = ffi::A::new().within_box(); another_heap_obj.as_mut().set(42); assert_eq!(another_heap_obj.get(), 42); } ``` -------------------------------- ### Generate Reproducible Case with `AUTOCXX_REPRO_CASE` Source: https://google.github.io/autocxx/print.html If minimization fails, use the `AUTOCXX_REPRO_CASE` environment variable to generate a reproducible case file. Specify `CLANG_PATH` or `CXX` if needed. ```bash AUTOCXX_REPRO_CASE=repro.json ``` -------------------------------- ### Test Bindgen Compatibility Source: https://google.github.io/autocxx/reporting_bugs.html Verify if a bug originates from bindgen by running it directly on the minimized header file. ```bash cargo run -- XYZ.hpp --no-layout-tests --enable-cxx-namespaces --allowlist-type ABC-- -std=c++14 ``` -------------------------------- ### Add autocxx and cxx to Cargo.toml Source: https://google.github.io/autocxx/tutorial.html Specify autocxx and cxx as dependencies and autocxx-build as a build dependency in your Cargo.toml file. Miette is optional but provides better error messages. ```toml [dependencies] autocxx = "0.30.0" cxx = "1.0" [build-dependencies] autocxx-build = "0.30.0" miette = { version = "5", features = ["fancy"] } # optional but gives nicer error messages! ``` -------------------------------- ### Configure Cargo dependencies for autocxx Source: https://google.github.io/autocxx/print.html Add the required autocxx and cxx dependencies to your Cargo.toml file. ```toml [dependencies] autocxx = "0.30.0" cxx = "1.0" [build-dependencies] autocxx-build = "0.30.0" miette = { version = "5", features = ["fancy"] } # optional but gives nicer error messages! ``` -------------------------------- ### Generate Rust bindings for a C++ class Source: https://google.github.io/autocxx/index.html Use include_cpp! to allowlist a class and interact with its methods using Rust. ```rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("Goat") // allowlist a type and all its methods } fn main() { let mut goat = ffi::Goat::new().within_unique_ptr(); // returns a cxx::UniquePtr, i.e. a std::unique_ptr goat.pin_mut().add_a_horn(); goat.pin_mut().add_a_horn(); assert_eq!(goat.describe().as_ref().unwrap().to_string_lossy(), "This goat has 2 horns."); } ``` -------------------------------- ### Configure FFI Safety Source: https://google.github.io/autocxx/print.html Demonstrates calling C++ functions with and without the safety!(unsafe) directive. ```cpp #include inline uint32_t do_math(uint32_t a, uint32_t b) { return a+b; } ``` ```rust use autocxx::prelude::*; include_cpp! { #include "input.h" generate!("do_math") } fn main() { assert_eq!(unsafe { ffi::do_math(12, 13) }, 25); } ``` ```cpp #include inline uint32_t do_math(uint32_t a, uint32_t b) { return a+b; } ``` ```rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe) generate!("do_math") } fn main() { assert_eq!(ffi::do_math(12, 13), 25); } ``` -------------------------------- ### Publish autocxx Crates Source: https://google.github.io/autocxx/contributing.html Run this script to perform cargo publish for all crates in the repository. ```bash tools/publish-all.sh ``` -------------------------------- ### Generate bindings with include_cpp Source: https://google.github.io/autocxx/print.html Use the include_cpp macro in your Rust source to specify headers and functions to generate. ```rust use autocxx::prelude::*; // use all the main autocxx functions include_cpp! { #include "my_header.h" // your header file name safety!(unsafe) // see details of unsafety policies described in the 'safety' section of the book generate!("DeepThought") // add this line for each function or type you wish to generate } ``` -------------------------------- ### Configure C++ Build Standards in build.rs Source: https://google.github.io/autocxx/building.html Use this configuration in your build script to specify C++ standards for both the autocxx builder and the underlying compiler. ```rust fn main() { let path = std::path::PathBuf::from("src"); // include path let mut b = autocxx_build::Builder::new("src/main.rs", &[&path]) .extra_clang_args(&["-std=c++17"]) .build() .unwrap(); b.flag_if_supported("-std=c++17") // use "-std:c++17" here if using msvc on windows .compile("autocxx-demo"); // arbitrary library name, pick anything println!("cargo:rerun-if-changed=src/main.rs"); // Add instructions to link to any C++ libraries you need. } ``` -------------------------------- ### Run autocxx engine tests with diagnostics Source: https://google.github.io/autocxx/contributing.html Execute specific tests with verbose logging and backtraces enabled to debug the conversion pipeline. ```bash RUST_BACKTRACE=1 RUST_LOG=autocxx_engine=info cargo test --all test_cycle_string_full_pipeline -- --nocapture ``` -------------------------------- ### Generate C++ burst Binding in Rust with Move Semantics Source: https://google.github.io/autocxx/print.html Generates Rust bindings for `Blimp` and `burst`. Demonstrates passing by copy and by move using `as_copy` and `as_mov`. ```rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("Blimp") generate!("burst") } fn main() { moveit! { let mut blimp = ffi::Blimp::new(); } ffi::burst(&*blimp); // pass by copy ffi::burst(as_copy(blimp.as_ref())); // explicitly say you want to pass by copy ffi::burst(as_mov(blimp)); // consume, using move constructor } ``` -------------------------------- ### Generate and use C++ bindings with autocxx Source: https://google.github.io/autocxx/cpp_functions.html Uses the include_cpp macro to define C++ headers and generate bindings for specific classes. Requires the unsafe_ffi safety setting to interact with the generated FFI. ```rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("Sloth") } fn main() { let mut sloth = ffi::Sloth::new().within_unique_ptr(); sloth.pin_mut().unpeel_from_tree(); sloth.pin_mut().unpeel_from_tree(); } ``` -------------------------------- ### Include C++ headers and generate bindings with include_cpp Source: https://google.github.io/autocxx/tutorial.html Use the include_cpp! macro in your Rust code to include C++ headers and specify which C++ types and functions to generate bindings for. Ensure you set the safety policy. ```rust use autocxx::prelude::*; include_cpp! { #include "my_header.h" // your header file name safety!(unsafe) // see details of unsafety policies described in the 'safety' section of the book generate!("DeepThought") // add this line for each function or type you wish to generate } ``` -------------------------------- ### Rust Main Function Using Generated Bindings Source: https://google.github.io/autocxx/print.html This Rust code shows how to use the generated bindings to interact with C++ code. It creates an instance of a C++ type 'A' using a generated function and then calls another generated function to handle it. ```rust fn main() { let a = dependent::create_a(base::B::VARIANT).within_unique_ptr(); dependent::handle_a(&a); } ``` -------------------------------- ### Generate Rust bindings for a C++ function Source: https://google.github.io/autocxx/index.html Use include_cpp! to allowlist and call the C++ function from Rust. ```rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("do_math") // allowlist a function } fn main() { assert_eq!(ffi::do_math(12, 13), 25); } ``` -------------------------------- ### Consume C++ objects in Rust Source: https://google.github.io/autocxx/print.html Demonstrates using autocxx to generate bindings for C++ objects and consuming them on the stack or heap. ```rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("Cake") generate!("eat") } fn main() { moveit! { let mut stack_cake = ffi::Cake::new(); } ffi::eat(stack_cake); // No more cake. // Still peckish. let heap_cake = ffi::Cake::new().within_unique_ptr(); ffi::eat(heap_cake); // Really no more cake now. } ``` -------------------------------- ### Include C++ header with autocxx Source: https://google.github.io/autocxx/allowlist.html Basic usage of the include_cpp macro to include a header file and generate bindings for a specific function. ```rust use autocxx::prelude::*; include_cpp! { #include "my_header.h" generate!("MyAPIFunction") } ``` -------------------------------- ### Define a simple C++ function Source: https://google.github.io/autocxx/index.html A basic C++ header file defining a function to be called from Rust. ```cpp #include inline uint32_t do_math(uint32_t a, uint32_t b) { return a+b; } ``` -------------------------------- ### Generate C++ feed_goat Binding in Rust Source: https://google.github.io/autocxx/print.html Generates Rust bindings for `Goat` and `feed_goat`. Demonstrates calling `feed_goat` with C++-like (copy) and Rust-like (consume) semantics. ```rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("Goat") generate!("feed_goat") } fn main() { let goat = ffi::Goat::new().within_unique_ptr(); // returns a cxx::UniquePtr, i.e. a std::unique_ptr // C++-like semantics... ffi::feed_goat(&goat); // ... you've still got the goat! ffi::feed_goat(&goat); // Or, Rust-like semantics, where the goat is consumed. ffi::feed_goat(goat); // No goat any more... // ffi::feed_goat(&goat); // doesn't compile } ``` -------------------------------- ### Call C++ function taking non-POD by value (Rust semantics) Source: https://google.github.io/autocxx/cpp_functions.html Demonstrates calling a C++ function that takes a non-POD type by value, using Rust-like semantics where the parameter is consumed. Requires the `autocxx::prelude::*` import. ```C++ #include struct Goat { Goat(); uint32_t horn_count; }; void feed_goat(Goat g); // takes goat by value ``` ```Rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("Goat") generate!("feed_goat") } fn main() { let goat = ffi::Goat::new().within_unique_ptr(); // returns a cxx::UniquePtr, i.e. a std::unique_ptr // C++-like semantics... ffi::feed_goat(&goat); // ... you've still got the goat! ffi::feed_goat(&goat); // Or, Rust-like semantics, where the goat is consumed. ffi::feed_goat(goat); // No goat any more... // ffi::feed_goat(&goat); // doesn't compile } ``` -------------------------------- ### Generate C++ take_string Binding in Rust Source: https://google.github.io/autocxx/print.html Generates Rust bindings for the C++ `take_string` function using autocxx. Demonstrates calling the C++ function from Rust. ```rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("take_string") } fn main() { assert_eq!(ffi::take_string("hello"), 5) } ``` -------------------------------- ### Use concrete! directive for C++ template instantiation in Rust Source: https://google.github.io/autocxx/print.html Demonstrates using the `concrete!` directive to provide a Rust name (`Boba`) for a C++ template instantiation (`Tea`). This allows `cxx::UniquePtr` to manage the type. ```rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("prepare") generate!("drink") concrete!("Tea", Boba) } fn main() { let nicer_than_it_sounds: cxx::UniquePtr = ffi::prepare(); ffi::drink(&nicer_than_it_sounds); } ``` -------------------------------- ### Referencing Automated Bindings from Manual cxx::bridge Source: https://google.github.io/autocxx/workflow.html Use a manual cxx::bridge module to define functions that reference types generated by an autocxx::include_cpp block. ```rust autocxx::include_cpp! { #include "foo.h" safety!(unsafe_ffi) generate!("take_A") generate!("A") } #[cxx::bridge] mod ffi2 { unsafe extern "C++" { include!("foo.h"); type A = crate::ffi::A; fn give_A() -> UniquePtr; // in practice, autocxx could happily do this } } fn main() { let a = ffi2::give_A(); assert_eq!(ffi::take_A(&a), autocxx::c_int(5)); } ``` -------------------------------- ### Upgrade autocxx Version Source: https://google.github.io/autocxx/contributing.html Execute this script to update the version number across the project during the release process. ```bash tools/upgrade-version.sh OLD NEW ``` -------------------------------- ### Implement C++ Observer in Rust Source: https://google.github.io/autocxx/rust_calls.html Rust implementation of a C++ subclass using the #[subclass] attribute and autocxx macros. ```rust use autocxx::prelude::*; use autocxx::subclass::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("register_observer") generate!("deregister_observer") generate!("feed_goat") subclass!("GoatObserver", MyGoatObserver) } use ffi::*; #[subclass] #[derive(Default)] pub struct MyGoatObserver; impl GoatObserver_methods for MyGoatObserver { fn goat_full(&self) { println!("BURP!"); } } impl Drop for MyGoatObserver { fn drop(&mut self) { deregister_observer(); } } fn main() { let goat_obs = MyGoatObserver::default_rust_owned(); // Register a reference to the superclass &ffi::GoatObserver register_observer(goat_obs.as_ref().borrow().as_ref()); feed_goat(); feed_goat(); feed_goat(); // prints BURP! } ``` -------------------------------- ### Convert C++ string constant to Rust string Source: https://google.github.io/autocxx/other_features.html Demonstrates accessing a C++ string constant as a byte array and converting it to a Rust string slice. ```rust # mod ffi { pub static BOB: [u8; 6] = [72u8, 101u8, 108u8, 108u8, 111u8, 0u8]; } assert_eq!(std::str::from_utf8(&ffi::BOB).unwrap().trim_end_matches(char::from(0)), "Hello"); ``` -------------------------------- ### Call C++ math function from Rust Source: https://google.github.io/autocxx/primitives.html Use include_cpp! to generate bindings for the C++ function and call it using c_int types. ```rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("do_math") } fn main() { assert_eq!(ffi::do_math(c_int(12), c_int(13)), c_int(25)); } ``` -------------------------------- ### Define C++ View and Tree structs with overloaded functions Source: https://google.github.io/autocxx/print.html Defines C++ types and overloaded 'saw' functions. ```cpp #include struct View { std::string of_what; // go and watch In Bruges, it's great }; struct Tree { int dendrochronologically_determined_age; }; void saw(const View&); void saw(const Tree&); ``` -------------------------------- ### Handle C++ function overloads in Rust Source: https://google.github.io/autocxx/cpp_functions.html Shows how autocxx handles C++ function overloads by appending numerical suffixes to the generated Rust function names (e.g., `saw`, `saw1`). Requires `rust-analyzer` for best IDE support. ```C++ #include struct View { std::string of_what; // go and watch In Bruges, it's great }; struct Tree { int dendrochronologically_determined_age; }; void saw(const View&); void saw(const Tree&); ``` ```Rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("Tree") generate!("View") generate!("saw") generate!("saw1") } fn main() { let view = ffi::View::new().within_unique_ptr(); ffi::saw(&view); let tree = ffi::Tree::new().within_unique_ptr(); ffi::saw1(&tree); // yuck, overload } ``` -------------------------------- ### Generate Bindings for C++ Namespaces Source: https://google.github.io/autocxx/naming.html Use `generate!("namespace::function")` to create Rust bindings for C++ functions within specific namespaces. Ensure all necessary C++ headers are included. ```C++ #include "input.h" namespace generations { void hey_boomer(); } namespace submarines { void hey_boomer(); } ``` ```Rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("submarines::hey_boomer") generate!("generations::hey_boomer") } fn main() { ffi::generations::hey_boomer(); // insults your elders and betters ffi::submarines::hey_boomer(); // launches missiles } ``` -------------------------------- ### Define a C++ struct for binding Source: https://google.github.io/autocxx/cpp_types.html A simple C++ header definition for a struct that will be exposed to Rust. ```cpp #include #include struct A { A() {} void set(uint32_t val); uint32_t get() const; uint32_t a; }; ``` -------------------------------- ### Call C++ function taking non-POD by value (C++ semantics) Source: https://google.github.io/autocxx/cpp_functions.html Illustrates calling a C++ function that takes a non-POD type by value, explicitly using C++-like copy semantics. The `as_copy` function can be used to ensure a copy is made. ```C++ #include struct Blimp { Blimp(); uint32_t tons_of_helium; }; void burst(Blimp b); // consumes blimp, // but because C++ is amazing, may copy the blimp first. ``` ```Rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("Blimp") generate!("burst") } fn main() { moveit! { let mut blimp = ffi::Blimp::new(); } ffi::burst(&*blimp); // pass by copy ffi::burst(as_copy(blimp.as_ref())); // explicitly say you want to pass by copy ffi::burst(as_mov(blimp)); // consume, using move constructor } ``` -------------------------------- ### Override C++ Methods in Rust Source: https://google.github.io/autocxx/rust_calls.html Rust implementation showing how to override or inherit C++ base class methods. ```rust use autocxx::prelude::*; use autocxx::subclass::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) subclass!("Dinosaur", TRex) subclass!("Dinosaur", Diplodocus) } use ffi::*; #[subclass] #[derive(Default)] pub struct TRex; #[subclass] #[derive(Default)] pub struct Diplodocus; impl Dinosaur_methods for TRex { // TRex does NOT implement the 'eat' method // so C++ behavior will be used } impl Dinosaur_methods for Diplodocus { fn eat(&self) { println!("Ahh, some nice juicy leaves."); // Could call self.eat_super() if we // developed unexpected carnivorous cravings. } } fn main() { let trex = TRex::default_rust_owned(); trex.borrow().as_ref().eat(); // eats human let diplo = Diplodocus::default_rust_owned(); diplo.borrow().as_ref().eat(); // eats shoots and leaves } ``` -------------------------------- ### C++ Header for Rust Bindings Source: https://google.github.io/autocxx/large_codebase.html This C++ header file defines the types and functions that will be exposed to Rust. Ensure this header is included in your C++ project. ```cpp #include struct A { A() : a(0) {} int a; }; enum B { VARIANT, }; void handle_a(const A& a); A create_a(B); ``` -------------------------------- ### Rust Module Definitions for C++ Integration Source: https://google.github.io/autocxx/print.html This Rust code demonstrates how to define C++ modules using autocxx. It includes definitions for C++ structs, enums, and functions, and specifies safety and generation rules. The 'base' module includes C++ types, while the 'dependent' module generates bindings for functions and references types from the 'base' module. ```rust #include struct A { A() : a(0) {} int a; }; enum B { VARIANT, }; void handle_a(const A& a); A create_a(B); ``` ```rust use autocxx::prelude::*; pub mod base { autocxx::include_cpp! { #include "input.h" name!(ffi2) safety!(unsafe_ffi) generate!("A") generate!("B") } pub use ffi2::*; } pub mod dependent { autocxx::include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("handle_a") generate!("create_a") extern_cpp_type!("A", crate::base::A) extern_cpp_type!("B", super::super::base::B) pod!("B") } pub use ffi::*; } ``` -------------------------------- ### Minimize Test Cases with creduce Source: https://google.github.io/autocxx/reporting_bugs.html Use this command to automatically reduce large C++ files into a minimal test case for reproducing bugs. ```bash cd tools/reduce; cargo run -- file -d "safety!(unsafe_ffi)" -d 'generate_pod!("A")' -I ~/my-include-dir -h my-header.h -p problem-error-message -- --remove-pass pass_line_markers ``` -------------------------------- ### Call C++ const method Source: https://google.github.io/autocxx/cpp_functions.html Demonstrates calling a `const` method on a C++ object from Rust. The method can be called directly on the object reference without special handling. ```C++ class Sloth { public: void sleep() const {} // sloths unchanged by sleep }; ``` ```Rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("Sloth") } fn main() { let sloth = ffi::Sloth::new().within_unique_ptr(); sloth.sleep(); sloth.sleep(); } ``` -------------------------------- ### Referencing Manual Bindings from autocxx Source: https://google.github.io/autocxx/workflow.html Use extern_cpp_opaque_type! to allow autocxx to reference types defined in a manual cxx::bridge module. ```rust autocxx::include_cpp! { #hexathorpe include "input.h" safety!(unsafe_ffi) generate!("handle_a") generate!("create_a") extern_cpp_opaque_type!("A", ffi2::A) } #[cxx::bridge] pub mod ffi2 { unsafe extern "C++" { include!("input.h"); type A; } impl UniquePtr {} } fn main() { let a = ffi::create_a(); ffi::handle_a(&a); } ``` -------------------------------- ### Call C++ overloaded functions in Rust Source: https://google.github.io/autocxx/print.html Shows how autocxx maps C++ overloads to suffixed Rust functions like 'saw' and 'saw1'. ```rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("Tree") generate!("View") generate!("saw") generate!("saw1") } fn main() { let view = ffi::View::new().within_unique_ptr(); ffi::saw(&view); let tree = ffi::Tree::new().within_unique_ptr(); ffi::saw1(&tree); // yuck, overload } ``` -------------------------------- ### Generate C++ Namespaced Functions in Rust Source: https://google.github.io/autocxx/print.html Generates Rust bindings for C++ functions within different namespaces. Demonstrates accessing these functions through Rust's module system. ```rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("submarines::hey_boomer") generate!("generations::hey_boomer") } fn main() { ffi::generations::hey_boomer(); // insults your elders and betters ffi::submarines::hey_boomer(); // launches missiles } ``` -------------------------------- ### Define C++ template Tea and struct Tapioca Source: https://google.github.io/autocxx/print.html Defines a C++ struct `Tapioca` and a templated struct `Tea`. The `prepare` function creates and returns a `Tea`, and `drink` accepts a const reference to `Tea`. ```cpp #include struct Tapioca { std::string yuck; }; template struct Tea { Tea() : floaters(nullptr) {} Floaters* floaters; }; inline Tea prepare() { Tea mixture; // prepare... return mixture; } inline void drink(const Tea&) {} ``` -------------------------------- ### Define a C++ class Source: https://google.github.io/autocxx/index.html A C++ class definition with methods and member variables. ```cpp #include #include class Goat { public: Goat(); ~Goat(); void add_a_horn(); std::string describe() const; private: uint32_t horns; }; ``` -------------------------------- ### Take String Size in C++ Source: https://google.github.io/autocxx/print.html Defines a C++ function that returns the size of a std::string. This is used to demonstrate passing strings between Rust and C++. ```cpp #include #include inline uint32_t take_string(std::string a) { return a.size(); } ``` -------------------------------- ### Call C++ const method from Rust Source: https://google.github.io/autocxx/print.html Demonstrates calling a const C++ method on a unique_ptr object. ```rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("Sloth") } fn main() { let sloth = ffi::Sloth::new().within_unique_ptr(); sloth.sleep(); sloth.sleep(); } ``` -------------------------------- ### Generate Rust Bindings with concrete! Directive Source: https://google.github.io/autocxx/cpp_types.html Using the concrete! directive in autocxx to map a C++ template instantiation to a specific Rust type name. ```rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe_ffi) generate!("prepare") generate!("drink") concrete!("Tea", Boba) } fn main() { let nicer_than_it_sounds: cxx::UniquePtr = ffi::prepare(); ffi::drink(&nicer_than_it_sounds); } ``` -------------------------------- ### Rust call to C++ with safety!(unsafe) Source: https://google.github.io/autocxx/safety.html Demonstrates calling the C++ `do_math` function from Rust without an explicit `unsafe` block. This is possible when `safety!(unsafe)` is used in the `include_cpp!` macro, indicating that the C++ code is guaranteed to be safe. ```rust use autocxx::prelude::*; include_cpp! { #include "input.h" safety!(unsafe) generate!("do_math") } fn main() { assert_eq!(ffi::do_math(12, 13), 25); } ```