I\'m very new to Rust. How would I return a String
from a Rust function that can be used in Python?
Here is my Rust implementation:
use
The problem here is that you are returning a CString
directly, which does not correspond to the representation of a string in C
(you can see here the source code of CString
).
You should be returning a pointer to the string, by using s.as_ptr()
. However, you need to make sure that the string is not deallocated at the end of the function, since that would result in a dangling pointer.
The only solution I can think of is to use forget
to let rust forget the variable instead of freeing it. Of course you will need to find a way to free the string later to avoid a memory leak (see Vladimir's answer).
With the changes I mentioned, your Rust code should be the following:
use std::ffi::CString;
use std::mem;
#[no_mangle]
pub extern fn query() -> *const i8 {
let s = CString::new("Hello!").unwrap();
let ptr = s.as_ptr();
mem::forget(s);
return ptr;
}