Andrew Wagner
Andrew Wagner

Reputation: 24547

How do you create a CString from a String in rust?

How does one create a std::ffi::CString from a String in Rust?

Assume the String is already stored in a variable that can be moved if necessary, NOT a literal like it is in many of the examples for constructing a CString.

I have studied the docs for both CString: https://doc.rust-lang.org/std/ffi/struct.CString.html

and String: https://doc.rust-lang.org/std/string/struct.String.html

and I still don't see the path. You must have to go through one of the many pointer types; Into and From aren't implemented for these types, so .into() doesn't work.

Upvotes: 8

Views: 7141

Answers (1)

Netwave
Netwave

Reputation: 42678

String implements Into<Vec<u8>> already:

use std::ffi::CString;


fn main() {
    let ss = "Hello world".to_string();
    let s = CString::new(ss).unwrap();
    println!("{:?}", s);
}

Playground

Upvotes: 8

Related Questions