Skip to content

Instantly share code, notes, and snippets.

@sunnyone
Last active September 20, 2021 10:13
Show Gist options
  • Save sunnyone/e660fe7f73e2becd4b2c to your computer and use it in GitHub Desktop.
Save sunnyone/e660fe7f73e2becd4b2c to your computer and use it in GitHub Desktop.
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