Build rules exercise

在 Chromium build 中,向 //ui/base/BUILD.gn 添加新的 Rust 目标,其中包含:

#![allow(unused)]
fn main() {
#[no_mangle]
pub extern "C" fn hello_from_rust() {
    println!("Hello from Rust!")
}
}

重要提示:请注意,在此处使用 no_mangle 会被Rust 编译器视为一种不安全行为,因此需要允许在“gn”目标中使用不安全的代码。

将这个新的 Rust 目标添加为 //ui/base:base 的依赖项。在 ui/base/resource/resource_bundle.cc 顶部声明此函数(稍后,我们将介绍如何通过绑定生成工具来自动执行此操作):

extern "C" void hello_from_rust();

ui/base/resource/resource_bundle.cc 中的某个位置调用此函数,我们建议在从 ResourceBundle::MaybeMangleLocalizedString 的顶部调用此函数。构建并运行 Chromium,并确保多次显示 “Hello from Rust!”。

如果您使用 VSCode,现在就请设置 Rust,以便其能在 VSCode 中正常运行。这对后续练习会很有帮助。如果操作成功,则可使用右键点击 println! 上的 “Go to definition”。

如何获取帮助

  • 适用于 [rust_static_library gn 模板] 的选项 (https://source.chromium.org/chromium/chromium/src/+/main:build/rust/rust_static_library.gni;l=16)
  • 关于 [#[no_mangle]] 的详细信息 (https://doc.rust-lang.org/beta/reference/abi.html#the-no_mangle-attribute)
  • 关于 [extern "C"] 的详细信息 (https://doc.rust-lang.org/std/keyword.extern.html)
  • 关于 gn 的 [--export-rust-project] 开关的详细信息 (https://gn.googlesource.com/gn/+/main/docs/reference.md#compilation-database)
  • 如何在 VSCode 中安装 rust-analyzer
It's really important that students get this running, because future exercises will build on it.

此示例很独特,因为其归根结底是最通用的互操作语言,即 C 语言。C++ 和 Rust 本身都可以声明和调用 C ABI 函数。在本课程的稍后部分,我们会直接将 C++ 和 Rust 关联起来。

此处需要使用 allow_unsafe = true,因为 #[no_mangle] 可能会支持 Rust 生成两个同名函数,而 Rust 无法保证会调用正确的函数。

如果需要纯 Rust 可执行文件,也可以使用 rust_executable gn 模板执行此操作。