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()
}
And crate-type = ["cdylib"]
It just works fine, but I'm not sure if there is a memory leak, because CString.from_raw is never called to deallocate the memory, according to the doc here CString in std::ffi - Rust
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.