Helpful Rust Windows API programming cheat sheet

Helpful cheat sheet for Windows programming in Rust


I’ll build this up over time as I go, anything I think is helpful as a quick reference guide & cheat sheet for certain windows programming patterns.

Strings

The following are some nice ways to handle strings in the Windows API when dealign with memory buffers.

// Null terminated UTF-8 buffer to String
String::from_utf8_lossy(ptr.as_bytes()).into_owned();

// Null terminated UTF-8 to str
str::from_utf8(ptr.as_bytes()).into_owned();

// LPWSTR to UTF16 String
let len = (0..).take_while(|&j| *lpwstr_variable.offset(j) != 0).count();
let raw_parts = std::slice::from_raw_parts(lpwstr_variable.as_ptr(), len);
let my_string = String::from_utf16_lossy(raw_parts);

// Create a PCSTR from a string/&str
let x = PCSTR::from_raw(my_string.as_ptr())

Buffers

Creating a buffer of dynamic size on the heap as a Vec of bytes, then writing to that buffer:

// In this exact example, out_str becomes a PSTR type for the API
let mut out_str: Vec<u8> = vec![0; MAX_PATH as _];
let mut len = out_str.len() as u32;

let res = unsafe {
    QueryFullProcessImageNameA(
        h_process, 
        PROCESS_NAME_FORMAT::default(), 
        PSTR::from_raw(out_str.as_mut_ptr()),
        &mut len,
    )
};