Skip to content

Instantly share code, notes, and snippets.

@iancormac84
Last active May 23, 2019 09:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iancormac84/4265a8f61ec59a8852c143da60fb6394 to your computer and use it in GitHub Desktop.
Save iancormac84/4265a8f61ec59a8852c143da60fb6394 to your computer and use it in GitHub Desktop.
How to work with WINAPI string types.
pub fn to_u16s<S: AsRef<OsStr>>(s: S) -> io::Result<Vec<u16>> {
fn inner(s: &OsStr) -> io::Result<Vec<u16>> {
let mut maybe_result: Vec<u16> = s.encode_wide().collect();
if maybe_result.iter().any(|&u| u == 0) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"strings passed to WinAPI cannot contain NULs",
)
.into());
}
maybe_result.push(0);
Ok(maybe_result)
}
inner(s.as_ref())
}
fn play_sound<S: AsRef<OsStr>>(file_name: S) -> io::Result<WhateverNonErrorTypeYouReturn> {
//Converts your &str into a Vec<u16>
let file_name = to_u16s(file_names)?;
//The .as_ptr() call provides a pointer to the Vec<u16>. The pointer is recognized as a LPCWSTR.
PlaySoundW(file_name.as_mut_ptr(), <other variables>);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment