0

[rust] Initial, quite minimal guidance around C++/Rust FFI.

Bug: None
Change-Id: Idfa0e5317d0e5cfb39949a30da234f5f056f40db
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/6388161
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Auto-Submit: Łukasz Anforowicz <lukasza@chromium.org>
Commit-Queue: Daniel Cheng <dcheng@chromium.org>
Cr-Commit-Position: refs/heads/main@{#1437017}
This commit is contained in:
Lukasz Anforowicz
2025-03-24 12:26:41 -07:00
committed by Chromium LUCI CQ
parent d5c1c21301
commit dcdb524a33
2 changed files with 39 additions and 9 deletions

38
docs/rust-ffi.md Normal file

@ -0,0 +1,38 @@
# Rust FFI
This document tries to provide guidance for C++/Rust FFI.
CLs to improve this guidance are welcomed.
## General guidance
Chromium recommends using [the `cxx` crate](https://cxx.rs/) for C++/Rust FFI.
For introductory guidance, please see
[the `cxx` chapter](https://google.github.io/comprehensive-rust/chromium/interoperability-with-cpp.html)
in the Chromium day of the Comprehensive Rust course.
Chromium also supports the following tools:
* [`bindgen`](https://rust-lang.github.io/rust-bindgen/) - see
`//build/rust/rust_bindgen.gni` for usage instructions.
At this point Chromium's `//build/rust/*.gni` templates do not support other FFI
tools like:
* [`cbindgen`](https://github.com/mozilla/cbindgen)
* [`crubit`](https://github.com/google/crubit)
### `cxx` guidance
#### Best practices
* Generate C++ side of bindings into a project-specific or crate-specific
`namespace`. For example: `#[cxx::bridge(namespace = "some_cpp_namespace")]`.
* Maintain binding declarations in a **single** `#[cxx::bridge]` declaration.
`cxx` supports reusing types across multiple `bridge`s, but there are some
rough edges.
#### Suggestions
TODO: Provide some examples or suggestions on how to structure FFI bindings
(even if these suggestions wouldn't necessarily rise to the level of "best
practices").

@ -237,15 +237,7 @@ GN template (not the built-in `rust_library`) to integrate properly into the
mixed-language Chromium build and get the correct compiler options applied to
them.
The [CXX](https://cxx.rs) tool is used for generating C++ bindings to Rust
code. Since it requires explicit declarations in Rust, an wrapper shim around a
pure Rust library is needed. Add these Rust shims that contain the CXX
`bridge` macro to the `cxx_bindings` GN variable in the `rust_static_library`
to have CXX generate a C++ header for that file. To include the C++ header
file, rooted in the `gen` output directory, use
```
#include "the/path/to/the/rust/file.rs.h"
```
See `rust-ffi.md` for information on C++/Rust FFI.
# Logging