DEV Community

Li
Li

Posted on

Convert String to CStr and back in rust

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);
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)