src/android/interoperability/java.md
Java can load shared objects via
Java Native Interface (JNI).
The jni crate allows you to create a compatible
library.
First, we create a Rust function to export to Java:
interoperability/java/src/lib.rs:
# // Copyright 2022 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
{{#include java/src/lib.rs:hello}}
interoperability/java/Android.bp:
{{#include java/Android.bp:libhello_jni}}
We then call this function from Java:
interoperability/java/HelloWorld.java:
{{#include java/HelloWorld.java:HelloWorld}}
interoperability/java/Android.bp:
{{#include java/Android.bp:helloworld_jni}}
Finally, you can build, sync, and run the binary:
{{#include ../build_all.sh:helloworld_jni}}
The unsafe(no_mangle) attribute instructs Rust to emit the
Java_HelloWorld_hello symbol exactly as written. This is important so that
Java can recognize the symbol as a hello method on the HelloWorld class.