简体   繁体   English

如何从 rust 中的字符串创建 CString?

[英]How do you create a CString from a String in rust?

How does one create a std::ffi::CString from a String in Rust?如何从 Rust 中的String创建std::ffi::CString

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 .假设String已经存储在一个可以在必要时移动的变量中,而不是像许多构造CString的示例中那样的文字。

I have studied the docs for both CString : https://doc.rust-lang.org/std/ffi/struct.CString.html我研究了两个CString的文档: https://doc.rust-lang.org/std/ffi/struct.CString.html

and String : https://doc.rust-lang.org/std/string/struct.String.htmlStringhttps://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;您必须通过多种指针类型之一来 go; Into and From aren't implemented for these types, so .into() doesn't work. IntoFrom没有为这些类型实现,所以.into()不起作用。

String implements Into<Vec<u8>> already: String已经实现了Into<Vec<u8>>

use std::ffi::CString;


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

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM