use std::ffi::CString;
use std::os::raw::c_char;
#[no_mangle]
pub extern fn hello() -> *mut c_char {
let s = CString::new("hello").unwrap();
s.into_raw()
}
The pointer which this function returns must be returned to Rust and reconstituted using from_raw to be properly deallocated. Specifically, one should not use the standard C free() function to deallocate this string.
Failure to call from_raw will lead to a memory leak.
Is it a correct way or any better way to do this? thanks!
Try check this jni crate. To properly run destructor for object which is passed to JVM you should interact with its GC, and the easiest workaround is just create java String from rust side with desired contents and pass it.
Thanks, yes, I believe JNI can workaround this issue, JNI will require much more code than JNR-FFI, and JNR-FFI is pretty straightforward to do bindings to native libraries without writing JNI code at all.