Seeking information regarding calling Rust from Java

Hi, I seek up to date information regarding calling Rust from Java (or Kotlin). Any information and links to official documentation appreciated.

I also posted a separate question about calling C from Rust, but I didn't include it in this question because I didn't want to confuse issues.

I'm new to Rust but I have significant C/C++ experience and I'm considering Rust but I am interested in its maturity. If I can call my existing C++ code (through extern C if needed) then switching to Rust may be feasible. Because I also want to interop with Java, that aspect is also important because if Rust can interop directly then I can use Rust as my first level layer from Java into lower level code including C/C++ if can call C/C++ form Rust.

Thank You!

There's different ways.

  • Go the manual route using jni and following the naming conventions (I think there was a macro crate that might help, can't remember its name)
  • Duchess, which uses JNI and provides safe abstractions on top.
  • uniffi, a bindings generator. It uses JNA under the hood and does the translation between Rust types, foreign types and the inbetween for you (disclaimer: I'm one of the maintainers)
1 Like

Thank you! Ordinarily I would think that FFI and thus uniffi would be the most performant option. However, JNA is generally less performant than both JNI and FFI, so would this relate to performance of uniffi?

FFI just stands for "Foreign function interface". By itself it cannot be "the most performant option" because it's not a thing of its own.
What you might have in mind is the specifics of the C calling convention. The JVM doesn't support that out of the box, that's why JNI exists.

UniFFI uses JNA under the hood. JNA does have some additional overhead and might be slower than pure JNI usage. UniFFI also does a whole lot more on top (automatic conversion between JVM types and Rust types, copying around stuff to make it safe, ...).
Whether that's performant enough for your use case you will have to determine yourself (we also don't have reliable benchmarks on that [yet]).

2 Likes

There's also robusta_jni — C interface for Rust // Lib.rs - it seems oddly hard to find Java interop libraries, though they do exists!

JEP 454: Foreign Function & Memory API , stabilized this year, outperforms jni by a large margin. I've had really good results at work using GitHub - mozilla/cbindgen: A project for generating C bindings from Rust code to generate a C header and GitHub - openjdk/jextract: https://openjdk.org/projects/code-tools to convert the C header to Java.

Several options. Thank you all kindly for the information!

@jer Yes, thank you. The recent FFM API is more specifically what I was referring to.

https://openjdk.org/jeps/454

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.