与 Java 的互操作性

Java可以通过 Java 本地接口 (JNI) 加载共享对象。jni crate 允许您创建一个兼容的库。

首先,我们创建一个可以导出到 Java 的 Rust 函数:

interoperability/java/src/lib.rs:

  1. #![allow(unused)]
  2. fn main() {
  3. //! Rust <-> Java FFI demo.
  4. use jni::objects::{JClass, JString};
  5. use jni::sys::jstring;
  6. use jni::JNIEnv;
  7. /// HelloWorld::hello method implementation.
  8. #[no_mangle]
  9. pub extern "system" fn Java_HelloWorld_hello(
  10. env: JNIEnv,
  11. _class: JClass,
  12. name: JString,
  13. ) -> jstring {
  14. let input: String = env.get_string(name).unwrap().into();
  15. let greeting = format!("Hello, {input}!");
  16. let output = env.new_string(greeting).unwrap();
  17. output.into_inner()
  18. }
  19. }

interoperability/java/Android.bp:

  1. rust_ffi_shared {
  2. name: "libhello_jni",
  3. crate_name: "hello_jni",
  4. srcs: ["src/lib.rs"],
  5. rustlibs: ["libjni"],
  6. }

We then call this function from Java:

interoperability/java/HelloWorld.java:

  1. class HelloWorld {
  2. private static native String hello(String name);
  3. static {
  4. System.loadLibrary("hello_jni");
  5. }
  6. public static void main(String[] args) {
  7. String output = HelloWorld.hello("Alice");
  8. System.out.println(output);
  9. }
  10. }

interoperability/java/Android.bp:

  1. java_binary {
  2. name: "helloworld_jni",
  3. srcs: ["HelloWorld.java"],
  4. main_class: "HelloWorld",
  5. required: ["libhello_jni"],
  6. }

最后,您可以构建、同步和运行二进制文件:

  1. m helloworld_jni
  2. adb sync # requires adb root && adb remount
  3. adb shell /system/bin/helloworld_jni