How to return a Rust Box in Java Native Interface?

Usually, returning Box<SomeStruct> is the way that FFI is done, as Box<SomeStruct> is a simple C pointer. However, suppose I want to create an instance of SomeStruct using Rust's JNI. On java I should return a jlong with the pointer number. How can I do it? Interpreting the Box as a number would make it be dropped after returning, which would give undefined behaviour.

#[no_mangle]
pub extern "system" fn Java_com_package_SomeStruct_new(_env: JNIEnv, _class: JClass) -> jlong {
    let some: Box<SomeStruct> = Box::new(SomeStruct::new());
    ???
}

Use Box::into_raw(my_box) and then Box::from_raw(ptr) when consuming the box.

@bjorn3 should I use from_raw to access the box and call methods on it, or just when I want to destruct it?

You can use unsafe { &*ptr } or unsafe { &mut *ptr } depending on if you need an immutable or mutable reference. Note that in case of a mutable reference you must ensure that there is no other reference to it (eg because another thread tried to call the same method)

1 Like

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.