Rust 库

您可以使用 rust_library 为 Android 创建一个新的 Rust 库。

在这里,我们声明了对两个库的依赖:

  • libgreeting, 我们在下面进行了定义,
  • libtextwrap, 一个已经在 external/rust/crates/ 中提供的 crate。

hello_rust/Android.bp:

1. rust_binary {
2. name: "hello_rust_with_dep",
3. crate_name: "hello_rust_with_dep",
4. srcs: ["src/main.rs"],
5. rustlibs: [
6. "libgreetings",
7. "libtextwrap",
8. ],
9. prefer_rlib: true, // Need this to avoid dynamic link error.
10. }

12. rust_library {
13. name: "libgreetings",
14. crate_name: "greetings",
15. srcs: ["src/lib.rs"],
16. }

hello_rust/src/main.rs:

1. //! Rust demo.

3. use greetings::greeting;
4. use textwrap::fill;

6. /// Prints a greeting to standard output.
7. fn main() {
8. println!("{}", fill(&greeting("Bob"), 24));
9. }

hello_rust/src/lib.rs:

1. //! Greeting library.

3. /// Greet `name`.
4. pub fn greeting(name: &str) -> String {
5. format!("Hello {name}, it is very nice to meet you!")
6. }

您可以像之前一样构建、推送和运行二进制文件:

1. m hello_rust_with_dep
2. adb push "$ANDROID_PRODUCT_OUT/system/bin/hello_rust_with_dep" /data/local/tmp
3. adb shell /data/local/tmp/hello_rust_with_dep
1. Hello Bob, it is very
2. nice to meet you!