How to automate Java bindings for Rust code?

I want to call Rust code in Java / Android, and I found 3 options:

JNI looks good and powerful enough, but you have to write too much code manually.

JNA , if you do not take into account that it crashes to my machine , you need to write a description of the data structure of the Rust structure manually in Java, the same problem with JNR FFI .

It is so interesting how difficult it will be to generate JNI code for traits and struct using macros or a compiler plugin? This compiler must match the implementation of attributes for a particular structure, as well as struct

 #[JNI] struct Foo { a: i32, } trait Boo { fn f(&self, b: f64) -> f64; } #[JNI] impl Boo for Foo { fn f(&self, b: f64) -> f64 { 0f64 } } 

and create Java classes for the struct and Java classes with native functions, and also generate pub no_mangle functions that wrap the feature functions.

+7
java rust jni jna
source share
3 answers

To provide the #[jni] annotations that work like this, you will need to use a compiler plugin. It would be an amazing tool, but so far it does not exist, as far as I know.

There are pieces of tools lying around that can be useful if you want to create a project that does this.

Plugins are currently unstable and do not work on non-night rust; you probably want to use syntex , which provides a stable interface for compiler plugins. You can also write a raw plugin (see here for the API for them), but most people will not be able to use it.

Here is rusty-cheddar , which generates c header files; You can take a look at this to see how it works. The author of this seems to be also working on a more general framework for creating bindings, but I don't know if he is active. You might be able to connect the cheddar output to something like JNAerator, but it probably won't create the most beautiful interfaces on the java side.

There are also rust-bindgen and corrode , which work in a different direction; they translate the headers c and arbitrary code c to rust, respectively. I do not know if this is really useful.

JNI-sys provides low-level JNI bindings; rust-on-mobile is a small project that uses it. Also see First Steps with Rust and Java , a blog post that shows some of the beginnings of getting things.

Lastly, a cbox that allows you to work with awkwardness with ownership and FFI.

+3
source share

Finally, I created such a project (link to the github repository) to automate the creation of the binding.

+3
source share

You can use jnaerator to automatically create structural mappings for JNA.

Alternatively, if you want to use JNI (and compile some more native code), you should go with SWIG .

0
source share

All Articles