Using JNI to call a Rust function that passes and returns a struct

I am new to Rust and now am trying to use JNI to call a Rust function that passes and returns a struct. A struct may define like this:

struct stud
	long int num;
	float score;

But since there is no struct in Java or JNI parameter conversion. I was thinking to create a corresponding class in Java. But don't know how to implement it.

I have googled this problem, there are very few references and just mentioned maybe I can use jlong. I am still very confused and don't know how to implement it.

Could anyone enlighten me or is there any reference or tutorial regarding this?

Thanks in advance!

You can look at what my tool generates and do the same:

For such code:

struct Strud {
    num: i64,
    score: f32,

fn my_func() -> Strud {

foreign_class!(class Strud {
    self_type Strud;
    private constructor = empty;
    fn num(&self) -> i64 {
    fn score(&self) -> f32 {

foreign_class!(class Statics {
    fn my_func() -> Strud;

it generates:

pub extern "C" fn Java_com_example_rust_Statics_do_1my_1func(env: *mut JNIEnv, _: jclass) -> jlong {
    let mut ret: Strud = my_func();
    let ret: jlong = <Strud>::box_object(ret);

where box_object looks like this:

        let this: Box<Strud> = Box::new(this);
        let this: *mut Strud = Box::into_raw(this);
        this as jlong

and one of access functions to data:

pub extern "C" fn Java_com_example_rust_Strud_do_1num(
    env: *mut JNIEnv,
    _: jclass,
    this: jlong,
) -> jlong {
    let this: &Strud = unsafe { jlong_to_pointer::<Strud>(this).as_mut().unwrap() };
    let mut ret: i64 = { this.num };
    let mut ret: jlong = ret;

generated Java code for Strud:

public final class Strud {
    /*package*/ long mNativeObj;

    private Strud() {}

    public final long num() {
        long ret = do_num(mNativeObj);

        return ret;
    private static native long do_num(long self);

Thank you!!

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.