Search code examples
windowswinapirustwindows-rs

Open a Key from Windows-Registry (winapi)


Hi i try to open a registry-key with the windows-crate (https://crates.io/crates/windows)

unsafe {
        let hkey: *mut HKEY = ptr::null_mut();        
        let reg_open_result = windows::Win32::System::Registry::RegOpenKeyExA(
            HKEY_LOCAL_MACHINE, 
            s!("SOFTWARE"),
            0 as u32,
            KEY_QUERY_VALUE,
            hkey
        );
        println!(">>> {:?}", reg_open_result);
        println!(">>> {:?}", hkey);
}

the macro s! is defined as follows:

#[macro_export]
macro_rules! s {
    ($s:literal) => {
        $crate::core::PCSTR::from_raw(::std::concat!($s, '\0').as_ptr())
    };
}

Calling this gives me WIN32_ERROR(87). I have no clue what im doing wrong here...


Solution

  • You're passing a null-pointer to RegOpenKeyExA in phkResult.

    phkResult: A pointer to a variable that receives a handle to the opened key.

    The variable should thus live on the stack and a pointer to it should be passed:

    unsafe {
            let mut hkey = HKEY(0);
            let reg_open_result = windows::Win32::System::Registry::RegOpenKeyExA(
                HKEY_LOCAL_MACHINE, 
                s!("SOFTWARE"),
                0 as u32,
                KEY_QUERY_VALUE,
                &mut hkey
            );
            println!(">>> {:?}", reg_open_result);
            println!(">>> {:?}", hkey);
    }