Hello,
I would like to know how to convert a &str to a std::ffi::CStr (not std::ffi::CString) ?
Thank you very much in advance for any help.
Hello,
I would like to know how to convert a &str to a std::ffi::CStr (not std::ffi::CString) ?
Thank you very much in advance for any help.
In the case where the str already ends with a null byte, you can:
use std::ffi::CStr;
fn str_to_cstr(s: &str) -> &CStr {
CStr::from_bytes_until_nul(s.as_bytes()).unwrap()
}
fn main() {
println!("{:?}", str_to_cstr("hello\0"));
}
If the str does not end with a null byte, then this conversion is impossible, because a &CStr must point to text which ends with a null byte, and a &-to-& conversion can’t change the contents of the memory the reference points to.
It's impossible, because CStr is only a view of existing data, with no place to store anything, but an existing &str does not have a \0 terminator.
So if I understand well I can only convert it to CString ?
Exactly. A CString provides space for that trailing null byte, which can be passed along to Cstr.
No, as I demonstrated, if you have strs that are already prepared to be C-string-compatible, then you can make &CStrs from them. Of course, this may be not applicable to your situation, but it is not impossible to do.
You can also write &CStr literals these days -- c"hello" includes the terminator.