打开Windows注册表中的一个键(winapi)

huangapple go评论91阅读模式
英文:

Open a Key from Windows-Registry (winapi)

问题

你好,我尝试使用 Windows-Crate(https://crates.io/crates/windows)打开注册表键。

```rust
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);
}

s! 定义如下:

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

调用它会得到 WIN32_ERROR(87)。我不知道我在这里做错了什么...

英文:

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

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

答案1

得分: 3

您正在将一个空指针传递给RegOpenKeyExA中的phkResult

phkResult:指向接收已打开的键的句柄的变量的指针。

因此,该变量应该位于堆栈上,并且应传递指向它的指针:

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);
}
英文:

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);
}

huangapple
  • 本文由 发表于 2023年7月27日 22:59:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76781041.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定