桥接模块

CXX依赖于提供的函数签名说明,这些签名会在不用语言之间进行交互使用。您可以在带有 #[cxx::bridge] 属性宏注解的 Rust 模块中使用 extern 代码块提供此说明。

#[allow(unsafe_op_in_unsafe_fn)] #[cxx::bridge(namespace = "org::blobstore")] mod ffi { // Shared structs with fields visible to both languages. struct BlobMetadata { size: usize, tags: Vec<String>, } // Rust types and signatures exposed to C++. extern "Rust" { type MultiBuf; fn next_chunk(buf: &mut MultiBuf) -> &[u8]; } // C++ types and signatures exposed to Rust. unsafe extern "C++" { include!("include/blobstore.h"); type BlobstoreClient; fn new_blobstore_client() -> UniquePtr<BlobstoreClient>; fn put(self: Pin<&mut BlobstoreClient>, parts: &mut MultiBuf) -> u64; fn tag(self: Pin<&mut BlobstoreClient>, blobid: u64, tag: &str); fn metadata(&self, blobid: u64) -> BlobMetadata; } }

Speaker Notes

  • 桥接通常在您的 crate 内的 ffi 模块中声明。
  • 根据在桥接模块中进行的声明,CXX 将生成匹配的 Rust 和 C++ 类型/函数定义,以便将这些内容公开给这两种语言。
  • 如需查看生成的 Rust 代码,请使用 cargo-expand 查看展开后的 proc 宏。对于大多数示例,您可以使用 cargo expand ::ffi 来仅展开 ffi 模块(但这不适用于 Android 项目)。
  • 如需查看生成的 C++ 代码,请在 target/cxxbridge 中查找。