Issue with using winapi to get char from scancode


I've been trying to convert between a scancode and a character. This system has worked before but as of now, for no reason that I can tell, has stopped working.

static mut SCANCODE_BUFFER: winapi::shared::minwindef::PBYTE = std::ptr::null_mut();
static mut layout: winapi::shared::minwindef::HKL = std::ptr::null_mut();

pub fn SCANCODE_TO_CHAR(scancode: u32) -> char {
    unsafe {
        let mut result = [0 as u16; 2];

        if GetKeyboardState(SCANCODE_BUFFER) ==  winapi::shared::minwindef::FALSE {
            return 0 as char;
        let vk = MapVirtualKeyExA(scancode, 1, layout);
        ToAsciiEx(vk, scancode, SCANCODE_BUFFER, result.as_mut_ptr(), 0, layout);
        result[0] as u8 as char  


pub fn initialize() {
    unsafe { 

        SCANCODE_BUFFER = [0 as u8; 256].as_mut_ptr();
        layout = GetKeyboardLayout(0);


I've done some debugging, and it seems that the function call: GetKeyboardState(SCANCODE_BUFFER)

Is causing the program to end with the this: (exit code: 0xc0000005, STATUS_ACCESS_VIOLATION)

Does anyone know how this might be fixed?

Extra info: SCANCODE_BUFFER is definitely not a null pointer.

asked on Stack Overflow Jun 15, 2020 by Skywalker1203

1 Answer


Sorry for posting this. SCANCODE_BUFFER was pointing to dropped memory. I must have been extremely lucky in the past.

answered on Stack Overflow Jun 15, 2020 by Skywalker1203

User contributions licensed under CC BY-SA 3.0