C++ 桥接声明

1. #[cxx::bridge]
2. mod ffi {
3. // C++ types and signatures exposed to Rust.
4. unsafe extern "C++" {
5. include!("include/blobstore.h");

7. type BlobstoreClient;

9. fn new_blobstore_client() -> UniquePtr<BlobstoreClient>;
10. fn put(self: Pin<&mut BlobstoreClient>, parts: &mut MultiBuf) -> u64;
11. fn tag(self: Pin<&mut BlobstoreClient>, blobid: u64, tag: &str);
12. fn metadata(&self, blobid: u64) -> BlobMetadata;
13. }
14. }

大致生成以下 Rust:

1. #[repr(C)]
2. pub struct BlobstoreClient {
3. _private: ::cxx::private::Opaque,
4. }

6. pub fn new_blobstore_client() -> ::cxx::UniquePtr<BlobstoreClient> {
7. extern "C" {
8. #[link_name = "org$blobstore$cxxbridge1$new_blobstore_client"]
9. fn __new_blobstore_client() -> *mut BlobstoreClient;
10. }
11. unsafe { ::cxx::UniquePtr::from_raw(__new_blobstore_client()) }
12. }

14. impl BlobstoreClient {
15. pub fn put(&self, parts: &mut MultiBuf) -> u64 {
16. extern "C" {
17. #[link_name = "org$blobstore$cxxbridge1$BlobstoreClient$put"]
18. fn __put(
19. _: &BlobstoreClient,
20. parts: *mut ::cxx::core::ffi::c_void,
21. ) -> u64;
22. }
23. unsafe {
24. __put(self, parts as *mut MultiBuf as *mut ::cxx::core::ffi::c_void)
25. }
26. }
27. }

29. // ...
  • 程序员无需承诺他们输入的签名准确无误。CXX 会执行静态断言,确认签名与 C++ 中声明的内容完全一致。
  • 借助 unsafe extern 代码块,您可以声明可从 Rust 安全调用的 C++ 函数。