mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-03-31 17:52:14 +02:00
1.2 KiB
1.2 KiB
Interoperability with Java
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:
{{#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 theJava_HelloWorld_hello
symbol exactly as written. This is important so that Java can recognize the symbol as ahello
method on theHelloWorld
class.- By default, Rust will mangle (rename) symbols so that a binary can link in two versions of the same Rust crate.