Rust Cheatsheet
Synopsis
Rust cheatsheet
Fun with strings
Types
String - Rust native owned string type (UTF-8 based) &str - borrowed reference to a String OsString - OS-specific owned string, esp. useful for Linux/Windows APIs OsStr - borrowed reference to OsString PCWSTR - 16bit string, used for Windows API
Conversions
Str -> &str: borrow reference with & PCWSTR -> String: PCWSTR::to_string() PCWSTR -> HSTRING: PCWSTR::to_hstring()
UTF-16 -> PCWSTR: PCWSTR::from_raw()
String -> PCWSTR
We convert the string to a OsString, append a \0 and take its address:
use std::ffi::OsString;
use std::os::windows::ffi::OsStrExt; // for converting between OsString and Windows-native string types
let my_string = "Hello, world!";
let wide_string: Vec<u16> = OsString::from(my_string).encode_wide().chain(Some(0)).collect();
let my_pwcstr: PCWSTR = PCWSTR::from_raw(wide_string.as_ptr());
Construction
literal -> PCWSTR: windows::w! macro