#java #jni #macro #natural #bindings #interface #function

ez_jni

Macros and functions that make using Java in rust feel natural

8 unstable releases (3 breaking)

new 0.5.4 Nov 23, 2024
0.5.3 Nov 22, 2024
0.4.0 Nov 10, 2024
0.3.0 Oct 20, 2024
0.1.0 Oct 6, 2024

#666 in Rust patterns

Download history 150/week @ 2024-10-05 23/week @ 2024-10-12 137/week @ 2024-10-19 10/week @ 2024-10-26 8/week @ 2024-11-02 99/week @ 2024-11-09 500/week @ 2024-11-16

628 downloads per month

Custom license

72KB
1K SLoC

GitHub Actions Workflow Status Crates.io Docs

EZ JNI

Closing the gap between Java and Rust. Check out the documentation page.


lib.rs:

EZ JNI

This library helps with creating Rust libraries or programs that can use Java code or be used by Java code.

If you are not familiar with the Java Native Interface, take a look at the JNI bindings.

Using Java from Rust

The call! macro is used to call Java methods. Specify the name of the method, as well as the Class if it is a static method, or the object (within parenthesis) the method belongs to. Then pass in parameters by specifying the Java Type, and the value (within parenthesis). The call will handle null return values and thrown exceptions if you use Option or Result (respectively) as the return type.

The new! macro can create new Object by calling the constructor. Specify the Class of the object you want to construct, and pass specify the parameters. You can also handle exceptions by using throws after the parameters and specifying an error type. The syntax is very similar to call!.

Using Rust from Java

A Rust or C function that can be called from Java must be named in a specific way and have a similar signature as the method on the Java side (see the JNI doc for more details). The jni_fn! macro takes a Rust function (with Java Types instead of Rust types) and makes it into one that can be called from Java.

These jni_fns are exported in the binary and serve as entrypoints to Rust from Java. The idea is similar to how Rust library crates have functions and types that are exported and used by other Rust packages.

Android and printing

Using the regular std::print (or any of its variants) will not work in Android because it seems that stdout and stderr redirect to /dev/null (for some reason). To get around this, replace those macros with the ones in this crate, which will call the right method to print in Android.

use ez_jni::{println, eprintln};

The downside is that the macro requires env to be a variable/argument that the macro can access, so you will only be able to print from functions that have the env passed into them.

Dependencies

~2–13MB
~99K SLoC