測試模組

CXX 的運作需要依照函式的型別敘述。這些敘述定義了從一種語言公開至另一種語言的介面。您會在具有 #[cxx::bridge] 屬性巨集註解的 Rust 模組中,使用外部區塊提供這項說明。

#[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 檢視已展開的程序巨集。在大多數範例中,您都會使用 cargo expand ::ffi,這樣就能只展開 ffi 模組 (但這不適用於 Android 專案)。
  • 如要檢視產生的 C++ 程式碼,請查看 target/cxxbridge