DEV Community

Li
Li

Posted on

1 1

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)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay