Skip to content

Instantly share code, notes, and snippets.

@dgellow
Created January 18, 2022 10:26
Show Gist options
  • Save dgellow/fb85229ee8aeabf3844a5f3d38eb445d to your computer and use it in GitHub Desktop.
Save dgellow/fb85229ee8aeabf3844a5f3d38eb445d to your computer and use it in GitHub Desktop.
Convert rust strings to win32 PWSTR type
use windows::Win32::Foundation::PWSTR;
#[derive(Default)]
pub struct WideString(pub Vec<u16>);
pub trait ToWide {
fn to_wide(&self) -> WideString;
}
impl ToWide for &str {
fn to_wide(&self) -> WideString {
let mut result: Vec<u16> = self.encode_utf16().collect();
result.push(0);
WideString(result)
}
}
impl ToWide for String {
fn to_wide(&self) -> WideString {
let mut result: Vec<u16> = self.encode_utf16().collect();
result.push(0);
WideString(result)
}
}
impl WideString {
pub fn as_pwstr(&self) -> PWSTR {
PWSTR(self.0.as_ptr() as *mut _)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment