The Bridge Module
CXX relies on a description of the function signatures that will be exposed from each language to the other. You provide this description using extern blocks in a Rust module annotated with the #[cxx::bridge] attribute macro.
1. #[allow(unsafe_op_in_unsafe_fn)]
2. #[cxx::bridge(namespace = "org::blobstore")]
3. mod ffi {
4. // Shared structs with fields visible to both languages.
5. struct BlobMetadata {
6. size: usize,
7. tags: Vec<String>,
8. }
10. // Rust types and signatures exposed to C++.
11. extern "Rust" {
12. type MultiBuf;
14. fn next_chunk(buf: &mut MultiBuf) -> &[u8];
15. }
17. // C++ types and signatures exposed to Rust.
18. unsafe extern "C++" {
19. include!("include/blobstore.h");
21. type BlobstoreClient;
23. fn new_blobstore_client() -> UniquePtr<BlobstoreClient>;
24. fn put(self: Pin<&mut BlobstoreClient>, parts: &mut MultiBuf) -> u64;
25. fn tag(self: Pin<&mut BlobstoreClient>, blobid: u64, tag: &str);
26. fn metadata(&self, blobid: u64) -> BlobMetadata;
27. }
28. }
- The bridge is generally declared in an
ffimodule within your crate. - From the declarations made in the bridge module, CXX will generate matching Rust and C++ type/function definitions in order to expose those items to both languages.
- To view the generated Rust code, use cargo-expand to view the expanded proc macro. For most of the examples you would use
cargo expand ::ffito expand just theffimodule (though this doesn’t apply for Android projects). - To view the generated C++ code, look in
target/cxxbridge.
