只要没有
0
字符串中的UTF-8代码单元,
name.as_bytes()
和
CString::new(name)?.as_bytes()
应该给你同样的字节。另外,
CString
.as_bytes_with_null()
只需附加一个
字节。下面是一个相当复杂的UTF-8字符串的小演示:
use std::ffi::CString;
fn main() {
let message: String = "\nÃÑ\u{1F601}".to_string();
println!("bytes_1: {:?}", message.as_bytes());
println!("bytes_2: {:?}", CString::new(message.clone()).unwrap().as_bytes());
println!("bytes_3: {:?}", CString::new(message.clone()).unwrap().as_bytes_with_nul());
}
结果与预期一致(您可能会认识到
10
,它对应于ASCII字符
\n
,其编码方式与UTF-8相同):
bytes_1: [10, 195, 159, 209, 137, 240, 159, 152, 129]
bytes_2: [10, 195, 159, 209, 137, 240, 159, 152, 129]
bytes_3: [10, 195, 159, 209, 137, 240, 159, 152, 129, 0]
如果字符串包含
U+0000
which is a valid Unicode code point
,由单个
0个
字节输入
UTF-8
,并且可以出现在普通字符串中。例如:
use std::ffi::CString;
fn main() {
let message: String = "\n\u{0000}\n\u{0000}".to_string();
println!("bytes_1: {:?}", message.as_bytes());
println!(
"bytes_2: {:?}",
match CString::new(message.clone()) {
Err(e) => format!("an error: {:?}, as expected", e),
Ok(_) => panic!("won't happen. .as_bytes() must fail."),
}
);
}
会给你
bytes_1: [10, 0, 10, 0]
bytes_2: "an error: NulError(1, [10, 0, 10, 0]), as expected"
.as_bytes()
成功了,但是
CString公司
名称。作为字节()
如果可能的话,UTF-8没有理由先把它转换成CString。