Skip to content

Instantly share code, notes, and snippets.

@sunnyone sunnyone/hello-u8.rs
Last active May 20, 2017

Embed
What would you like to do?
Windows Unicode conversion in Rust
// Add to Cargo.toml
// [dependencies]
// winapi = "*"
// user32-sys = "*"
extern crate winapi;
extern crate user32;
fn from_wide_ptr(ptr: *const u16) -> String {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
unsafe {
assert!(!ptr.is_null());
let len = (0..std::isize::MAX).position(|i| *ptr.offset(i) == 0).unwrap();
let slice = std::slice::from_raw_parts(ptr, len);
OsString::from_wide(slice).to_string_lossy().into_owned()
}
}
fn to_wide_chars(s: &str) -> Vec<u16> {
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
OsStr::new(s).encode_wide().chain(Some(0).into_iter()).collect::<Vec<_>>()
}
use std::fmt;
use std::ptr;
#[no_mangle]
pub extern "C" fn hello2(ptr: *const u16) {
let y = from_wide_ptr(ptr);
println!("X: {}", y);
unsafe {
user32::MessageBoxW(ptr::null_mut(),
to_wide_chars(&format!("こんにちは: {}", y)).as_ptr(),
to_wide_chars("世界").as_ptr(),
0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.