呼叫 Rust
您可以輕鬆將 Rust 函式和型別匯出至 C:
__interoperability/rust/libanalyze/analyze.rs
__interoperability/rust/libanalyze/analyze.h
#ifndef ANALYSE_H
#define ANALYSE_H
extern "C" {
void analyze_numbers(int x, int y);
}
#endif
__interoperability/rust/libanalyze/Android.bp
rust_ffi {
name: "libanalyze_ffi",
crate_name: "analyze_ffi",
srcs: ["analyze.rs"],
include_dirs: ["."],
}
我們現在可以從 C 二進位檔呼叫此介面:
__interoperability/rust/analyze/main.c
#include "analyze.h"
int main() {
analyze_numbers(10, 20);
analyze_numbers(123, 123);
return 0;
}
__interoperability/rust/analyze/Android.bp
cc_binary {
name: "analyze_numbers",
srcs: ["main.c"],
static_libs: ["libanalyze_ffi"],
}
建構、推送及在裝置上執行二進位檔:
m analyze_numbers
adb push "$ANDROID_PRODUCT_OUT/system/bin/analyze_numbers" /data/local/tmp
adb shell /data/local/tmp/analyze_numbers
Speaker Notes
#[no_mangle]
會停用 Rust 的一般名稱改編功能,因此匯出的符號將只是函式名稱。您也可以使用 #[export_name = "some_name"]
指定任何名稱。