编者注:此代码示例来自1.0之前的Rust版本,并且不是有效的Rust 1.0代码,但是答案仍然包含有价值的信息。
我想将字符串文字传递给Windows API。许多Windows函数使用UTF-16作为字符串编码,而Rust的本机字符串是UTF-8。
我知道Rust有utf16_units()来生成UTF-16字符迭代器,但是我不知道如何使用该函数来生成UTF-16字符串(最后一个字符为零)。
我正在生成这样的UTF-16字符串,但我确信有更好的方法来生成它:
extern "system" {
pub fn MessageBoxW(hWnd: int, lpText: *const u16, lpCaption: *const u16, uType: uint) -> int;
}
pub fn main() {
let s1 = [
'H' as u16, 'e' as u16, 'l' as u16, 'l' as u16, 'o' as u16, 0 as u16,
];
unsafe {
MessageBoxW(0, s1.as_ptr(), 0 as *const u16, 0);
}
}
Run Code Online (Sandbox Code Playgroud) #![allow(non_camel_case_types)]
use libc::{c_uchar, size_t};
use std::str::FromStr;
use std::ffi::{CString, NulError};
use std::slice;
#[repr(C)]
pub struct c_str_t {
pub len: size_t,
pub data: *const c_uchar,
}
pub trait MyCStrExt<T> {
fn to_c_str(&self) -> Result<c_str_t, NulError>;
}
pub trait MyCStringExt {
fn from_c_str_ref(nstr: &c_str_t) -> Option<String>;
}
impl<'a> MyCStrExt<&'a str> for str {
fn to_c_str(&self) -> Result<c_str_t, NulError> {
let result = match CString::new(&self[..]) {
Ok(result) => result,
Err(e) => {
return Err(e);
}
};
Ok(c_str_t { data: result.as_ptr() as *const u8, len: …Run Code Online (Sandbox Code Playgroud)