Just some code snippets to convert rust String
to std::ffi::CStr
/std::ffi::CString
and back.
String to CString/CStr
use std::ffi::CStr;
use std::ffi::CString;
fn main() {
let s = "Hello World!".to_string();
let c_string: CString = CString::new(s.as_str()).unwrap();
let c_str: &CStr = c_string.as_c_str();
println!("{:?}", c_str);
}
CStr to String
use std::ffi::CStr;
fn main() {
let c_str: &CStr = CStr::from_bytes_with_nul(b"Hello World!\0").unwrap();
let s: String = c_str.to_string_lossy().into_owned();
println!("{:?}", s);
}
Top comments (0)