绑定示例

CXX requires that the whole C++/Rust boundary is declared in cxx::bridge modules inside .rs source code.

  1. #[cxx::bridge]
  2. mod ffi {
  3. extern "Rust" {
  4. type MultiBuf;
  5. fn next_chunk(buf: &mut MultiBuf) -> &[u8];
  6. }
  7. unsafe extern "C++" {
  8. include!("example/include/blobstore.h");
  9. type BlobstoreClient;
  10. fn new_blobstore_client() -> UniquePtr<BlobstoreClient>;
  11. fn put(self: &BlobstoreClient, buf: &mut MultiBuf) -> Result<u64>;
  12. }
  13. }
  14. // 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 a mod called ffi 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++ 编译器 使用。