调用 Rust

将 Rust 函数和类型导出到 C 很简单:

interoperability/rust/libanalyze/analyze.rs

  1. //! Rust FFI demo.
  2. #![deny(improper_ctypes_definitions)]
  3. use std::os::raw::c_int;
  4. /// Analyze the numbers.
  5. #[no_mangle]
  6. pub extern "C" fn analyze_numbers(x: c_int, y: c_int) {
  7. if x < y {
  8. println!("x ({x}) is smallest!");
  9. } else {
  10. println!("y ({y}) is probably larger than x ({x})");
  11. }
  12. }

interoperability/rust/libanalyze/analyze.h

  1. #ifndef ANALYSE_H
  2. #define ANALYSE_H
  3. extern "C" {
  4. void analyze_numbers(int x, int y);
  5. }
  6. #endif

interoperability/rust/libanalyze/Android.bp

  1. rust_ffi {
  2. name: "libanalyze_ffi",
  3. crate_name: "analyze_ffi",
  4. srcs: ["analyze.rs"],
  5. include_dirs: ["."],
  6. }

我们现在可以从一个 C 二进制文件中调用它:

interoperability/rust/analyze/main.c

  1. #include "analyze.h"
  2. int main() {
  3. analyze_numbers(10, 20);
  4. analyze_numbers(123, 123);
  5. return 0;
  6. }

interoperability/rust/analyze/Android.bp

  1. cc_binary {
  2. name: "analyze_numbers",
  3. srcs: ["main.c"],
  4. static_libs: ["libanalyze_ffi"],
  5. }

在你的设备上构建,推送,并运行二进制文件 :

  1. m analyze_numbers
  2. adb push "$ANDROID_PRODUCT_OUT/system/bin/analyze_numbers" /data/local/tmp
  3. adb shell /data/local/tmp/analyze_numbers

#[no_mangle] 禁用了 Rust 通常的名称重整,因此导出的符号将仅为函数的名称。你还可以使用 #[export_name = "some_name"] 来指定任意你想要的名称。