Build rules exercise
在您的 Chromium 版本中,將新的 Rust 目標加至 //ui/base/BUILD.gn,其中包含以下內容:
#![allow(unused)] fn main() { #[no_mangle] pub extern "C" fn hello_from_rust() { println!("Hello from Rust!") } }
Important: note that no_mangle here is considered a type of unsafety by the Rust compiler, so you’ll need to allow unsafe code in your gn target.
將這個新的 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,讓 Rust 在 VSCode 中順利運作。這在後續練習中會很實用。如果您成功完成,就能在 println! 中以滑鼠右鍵按一下「Go to definition」。
如何找到說明
rust_static_librarygn 範本提供的選項#[no_mangle]相關資訊extern "C"相關資訊- gn 的
--export-rust-projectswitch 相關資訊 - 如何在 VSCode 中安裝 rust-analyzer
此範例會探究做為最小公因數的互通語言 C,因此很特別。C++ 和 Rust 都能以原生方式宣告及呼叫 C ABI 函式。本課程稍後會將 C++ 直接連結至 Rust。
這裡需要 allow_unsafe = true,因為 #[no_mangle] 可能會允許 Rust 產生兩個名稱相同的函式,Rust 就不再能保證系統會呼叫正確的函式。
如果需要純 Rust 執行檔,也可以使用 rust_executable gn 範本執行這項操作。