How to use windows-rust to call FormatMessageW correctly? I want to get a demo or sample.

Virtual CC 0 Reputation points
2023-03-17T05:47:59.8066667+00:00
use std::{env, ptr::NonNull};
use windows::{Win32::System::Diagnostics::Debug::*,
    core::*, imp::heap_free,};


fn main() {
    let args: Vec<String> = env::args().collect();

    if args.len() < 2 {
        println!("Usage: ShowError <number>");
        return;
    }

    let message:u32 = args[1].parse().unwrap();

    let mut text = HeapString(std::ptr::null_mut());
    unsafe{
        let chars = FormatMessageW(
            FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_IGNORE_INSERTS,
            None, message, 
            0, 
            PWSTR(&mut text.0 as *mut _ as *mut _),
            0, None);
        if chars > 0 {
            println!("Message {}: {:?}",message,text);
        }
        else{
            println!("No such error exists");
        }
    }

}

#[derive(Debug)]
struct HeapString(*mut u16);

impl Drop for HeapString{
    fn drop(&mut self) {
        if !self.0.is_null(){
            unsafe{
                heap_free(self.0 as _);
            }
        }
    }
}
Community Center | Not monitored
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Virtual CC 0 Reputation points
    2023-03-17T10:41:24.08+00:00
    let chars = FormatMessageW(
                FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                None, message, 
                0,
                PWSTR(&mut text.0 as *mut _ as *mut _),
                0,None);
            if chars > 0 {
                let parts = std::slice::from_raw_parts(text.0, chars as _);
                println!("Message {}: {:?}",message,String::from_utf16(parts).unwrap());
            }
            else{
                let errcode = GetLastError();
                println!("No such error exists error: {}",errcode);
            }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.