绑定示例
CXX requires that the whole C++/Rust boundary is declared in cxx::bridge
modules inside .rs
source code.
#[cxx::bridge]
mod ffi {
extern "Rust" {
type MultiBuf;
fn next_chunk(buf: &mut MultiBuf) -> &[u8];
}
unsafe extern "C++" {
include!("example/include/blobstore.h");
type BlobstoreClient;
fn new_blobstore_client() -> UniquePtr<BlobstoreClient>;
fn put(self: &BlobstoreClient, buf: &mut MultiBuf) -> Result<u64>;
}
}
// Definitions of Rust types and functions go here
指出:
- Although this looks like a regular Rust
mod
, the#[cxx::bridge]
procedural macro does complex things to it. The generated code is quite a bit more sophisticated - though this does still result in amod
calledffi
in your code. - Native support for C++'s
std::unique_ptr
in Rust - Native support for Rust slices in C++
- 从 C++ 调用 Rust,并使用 Rust 类型(顶部位置)
- 从 Rust 调用 C++,并使用 C++ 类型(底部位置)
常见误解:这 看似 Rust 在解析 C++ 头文件,其实具有误导性。Rust 不会对此头文件进行解释,只是在生成的 C++ 代码中添加 #include
,以便于 C++ 编译器 使用。