How can Rust function get an array from Java and return an array to Java?


I’m trying to creating a Rust dynamic library to be called by Java.

From , I learned that Rust function can get an integer and return an integer.

However, I do not know how to make Rust function get an integer array from Java and return an integer array.

I would be glad if you teach me how to achieve that.



You will need to export your function using Java Native Interface (JNI) and use the JNI type for integer array.

In Rust code, you can use the jni-rs crate and write something like this:

    extern crate jni;

    use jni::JNIEnv;
    use jni::objects::JClass;
    use jni::sys::jintArray;

    pub extern "C" fn Java_com_example_MyClass_transformArray(env: JNIEnv, _: JClass, array: jintArray) -> jintArray {
        // ...

The name of the function specify how it can be called from Java.
Here, this function will be accessible in Java from the method transformArray in the class com.example.MyClass.

class MyClass {
    private static native int[] transformArray(int[] array);


Thanks for your reply. I’ll try jni-rs.


You can do it in simple way with rust_swig:

fn rust_func(a: &[i32]) -> &[i32] {

foreigner_class!(class Utils {
    static_method rust_func(_: &[i32]) -> &[i32];

You just need implement rust_func all other stuff (creation of Java_…) functions convert to/from jintArray, generate Java Utils class,
all of that rust_swig does for you.


Thanks for your comment. rust_swig looks nice. I will check it.