前提条件
在本教程中,您将使用创建 FIDL 库教程中的 fuchsia.examples
FIDL 库。此 FIDL 库的代码可以在 //examples/fidl/fuchsia.examples 中找到。请花点时间查看代码,然后再继续。
概览
本教程详细介绍了如何在 Rust 中使用 FIDL,方法是创建一个可用作探索 Rust 绑定的“测试平台”的单元测试。
本文档介绍了如何完成以下任务:
示例代码位于 //examples/fidl/rust/fidl_crates/
中的 Fuchsia 结账部分。如果您希望按照本教程中的说明编写所有代码,则可以移除示例代码:
rm -r examples/fidl/rust/fidl_crates/*
编写“hello world”程序
将主函数添加到
examples/fidl/rust/fidl_crates/src/main.rs
:fn main() { println!("Hello, world!"); }
定义
rustc_binary
,然后通过$host_toolchain
创建对测试的依赖项,这将为主机构建二进制文件。为此,请将以下代码添加到examples/fidl/rust/fidl_crates/BUILD.gn
中:import("//build/rust/rustc_binary.gni") rustc_binary("fidl_crates_bin") { edition = "2021" sources = [ "src/main.rs" ] } group("fidl_crates") { testonly = true deps = [ ":fidl_crates_bin($host_toolchain)" ] }
在 build 中包含示例
fx set core.x64 --with //examples/fidl/rust/fidl_crates
构建示例
fx build
运行二进制文件
out/default/host_x64/fidl_crates_bin
您应该会看到输出了 hello world 消息。
将 Rust FIDL 绑定添加为依赖项
对于每项 FIDL 库声明(包括编译 FIDL 中的声明),在原始目标名称后附加 _rust
会生成一个包含相应库的 Rust 绑定代码的 FIDL crate。
通过引用以下生成的 crate,添加对 Rust 绑定的依赖项。新的 rustc_binary
目标应如下所示:
rustc_binary("fidl_crates_bin") {
edition = "2021"
deps = [ "//examples/fidl/fuchsia.examples:fuchsia.examples_rust" ]
sources = [ "src/main.rs" ]
}
(可选)如需查看新生成的绑定,请执行以下操作:
- 请使用
fx build
重新构建。 - 切换到生成的文件目录:
out/default/fidling/gen/examples/fidl/fuchsia.examples/fuchsia.examples
。生成的代码位于fidl_fuchsia_examples.rs
中。如果您设置了不同的 build 输出目录,则可能需要更改out/default
。您可以使用cat .fx-build-dir
检查构建输出目录。
如需详细了解如何查找生成的绑定代码,请参阅查看生成的绑定代码。
在项目中使用 FIDL Rust crate
添加测试模块和占位符测试,创建一个测试所生成的 FIDL crate 的地方:
#[cfg(test)]
mod test {
#[test]
fn fidl_crates_usage() {
}
}
然后,您需要通过设置 with_unit_tests
实参来构建测试:
rustc_binary("fidl_crates_bin") {
edition = "2021"
test_deps = [ "//examples/fidl/fuchsia.examples:fuchsia.examples_rust" ]
with_unit_tests = true
sources = [ "src/main.rs" ]
}
这将生成一个 fidl_crates_bin_test
目标,然后应将其添加到 build 组中:
group("fidl_crates") {
testonly = true
deps = [
":fidl_crates_bin($host_toolchain)",
":fidl_crates_bin_test($host_toolchain)",
]
}
如需导入 crate,请将以下代码添加到 tests
模块的顶部。在 Fuchsia 树中,为简洁起见,FIDL crate 通常简称为较短的名称:
use fidl_fuchsia_examples as fex;
使用生成的绑定代码
现在,您可以使用生成的绑定代码编写一些代码。如需详细了解这些绑定,请参阅 Rust 绑定参考文档。
您还可参考下面的示例代码,开始了解这些功能。您可以在 fidl_crates_usage
测试中添加以下代码:
let flags = fex::FileMode::READ | fex::FileMode::WRITE;
println!("{:?}", flags);
let from_raw = fex::LocationType::from_primitive(1).expect("Could not create LocationType");
assert_eq!(from_raw, fex::LocationType::Museum);
assert_eq!(fex::LocationType::Restaurant.into_primitive(), 3);
let red = fex::Color { id: 0u32, name: "red".to_string() };
println!("{:?}", red);
let int_val = fex::JsonValue::IntValue(1);
let str_val = fex::JsonValue::StringValue("1".to_string());
println!("{:?}", int_val);
assert_ne!(int_val, str_val);
let user = fex::User { age: Some(20), ..Default::default() };
println!("{:?}", user);
assert!(user.age.is_some());
如需重新构建并重新运行测试,请运行以下命令:
fx test -vo fidl_crates_bin_test