C++ Bridge Declarations

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. }

Results in (roughly) the following 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. // ...
  • The programmer does not need to promise that the signatures they have typed in are accurate. CXX performs static assertions that the signatures exactly correspond with what is declared in C++.
  • unsafe extern blocks allow you to declare C++ functions that are safe to call from Rust.