Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

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.

like image 401
Andrew Wagner Avatar asked Apr 07 '26 22:04

Andrew Wagner


1 Answers

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

like image 194
Netwave Avatar answered Apr 10 '26 13:04

Netwave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!