ブリッジモジュール
CXX では、各言語からもう一方の言語に公開される関数シグネチャの記述が 必要です。この記述は、#[cxx::bridge] 属性マクロが付いた Rust モジュール内の extern ブロックを使って提供します。
// Copyright 2023 Google LLC
// SPDX-License-Identifier: Apache-2.0
#[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;
}
}
- ブリッジは通常、クレート内の
ffiモジュールで宣言します。 - ブリッジモジュール内で行った宣言から、CXX は対応する Rust と C++ の 型/関数定義を生成し、それらの項目を両方の言語に公開します。
- 生成された Rust コードを確認するには、cargo-expand を使って展開された proc macro を表示します。ほとんどの例では、
ffiモジュールだけを展開するためにcargo expand ::ffiを使用します(ただし、これは Android プロジェクトには当てはまりません)。 - 生成された C++ コードを確認するには、
target/cxxbridgeを参照してください。