桥接模块

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

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