Using cxx in Chromium

在 Chromium 中,针对每个需要使用 Rust 的叶节点,我们定义独立的 #[cxx::bridge] mod。通常,每个 rust_static_library 都有对应的定义。只需将

cxx_bindings = [ "my_rust_file.rs" ]
   # list of files containing #[cxx::bridge], not all source files
allow_unsafe = true

添加到您现有的 rust_static_library 以及 crate_rootsources 的目标中。

C++ 头文件会在合理的位置生成,因此您只需

#include "ui/base/my_rust_file.rs.h"

您会发现,//base 中提供了一些实用函数,可将 Chromium C++ 类型与 CXX Rust 类型相互转换,例如 SpanToRustSlice

学生可能会问:为什么我们仍然需要 allow_unsafe = true

总的来说,按照常规 Rust 标准,没有任何 C/C++ 代码是 “安全”的。在 Rust 中来回调用 C/C++ 可能会对内存执行任意操作,并危及 Rust 自身数据布局的安全性。如果 C/C++ 互操作性中出现 过多unsafe 关键字,可能会损害此类关键字的信噪比,并且 存在争议。但严格地说,将任何外部代码引入 Rust 二进制文件可能会导致 Rust 中出现意外行为。

The narrow answer lies in the diagram at the top of this page — behind the scenes, CXX generates Rust unsafe and extern "C" functions just like we did manually in the previous section.