C++ のブリッジ宣言

#[cxx::bridge] mod ffi { // Rust に公開される C++ の型とシグネチャ。 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; } }

おおよそ次のような Rust が生成されます。

#[repr(C)] pub struct BlobstoreClient { _private: ::cxx::private::Opaque, } pub fn new_blobstore_client() -> ::cxx::UniquePtr<BlobstoreClient> { extern "C" { #[link_name = "org$blobstore$cxxbridge1$new_blobstore_client"] fn __new_blobstore_client() -> *mut BlobstoreClient; } unsafe { ::cxx::UniquePtr::from_raw(__new_blobstore_client()) } } impl BlobstoreClient { pub fn put(&self, parts: &mut MultiBuf) -> u64 { extern "C" { #[link_name = "org$blobstore$cxxbridge1$BlobstoreClient$put"] fn __put( _: &BlobstoreClient, parts: *mut ::cxx::core::ffi::c_void, ) -> u64; } unsafe { __put(self, parts as *mut MultiBuf as *mut ::cxx::core::ffi::c_void) } } } // ...

Speaker Notes

  • プログラマーは、入力したシグネチャが正確であることを保証する必要はありません。CXX は、シグネチャが C++ で宣言されたものと完全に対応するということを静的に保証します。
  • unsafe extern ブロックを使用すると、Rust から安全に呼び出せる C++ 関数を宣言できます。