简体   繁体   English

C ++-从注册表读取的值中获取空值

[英]C++ - getting null values in value read from registry

My application properly reads and writes to the registry. 我的应用程序正确读取和写入注册表。 Now, I need to read a registry value from: 现在,我需要从以下位置读取注册表值:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\MachineGuid

Here is my code: 这是我的代码:

bool GetWindowsID(string &winID)
{
    HKEY hKey = 0, hKeyType = HKEY_LOCAL_MACHINE;
    bool status = false;
    DWORD dwType = 0;
    DWORD dwBufSize = 256;
    char value[256] = "\0";
    if (RegOpenKeyEx(hKeyType, L"SOFTWARE\\Microsoft\\Cryptography", NULL, KEY_QUERY_VALUE|KEY_WOW64_64KEY, &hKey) == ERROR_SUCCESS)
    {
        dwType = REG_SZ;
        if (RegQueryValueEx(hKey, L"MachineGuid", NULL, &dwType, (LPBYTE)value, &dwBufSize) == ERROR_SUCCESS)
            status = true;
        RegCloseKey(hKey);
    }
    winID.assign(value);
    return status;
}

I get the guid but in value array after each character their is a "\\0" value due to which only first character of array gets assigned to string. 我得到了guid但是在value数组中,每个字符之后的value都是“ \\ 0”值,这是因为只有数组的第一个字符才分配给字符串。 This is wierd! 这太奇怪了!

在此处输入图片说明

You have built targeting Unicode and so the registry API is returning UTF-16 Unicode text. 您已经建立了针对Unicode的目标,因此注册表API返回了UTF-16 Unicode文本。 Instead of char use wchar_t and remember that each wchar_t element is 2 bytes wide. 请记住,每个wchar_t元素的宽度为2个字节,而不是char使用wchar_t

Do also make sure that you account for the returned string not being null-terminated, as described in the documentation. 还请确保按照文档中的说明,说明返回的字符串不是空终止的。 You must take account of the value returned in dwBufSize . 您必须考虑dwBufSize返回的值。

I get the guid but in value array after each character their is a "\\0" value due to which only first character of array gets assigned to string. 我得到了GUID,但是在值数组中,每个字符之后的值都是“ \\ 0”值,这是因为只有数组的第一个字符才分配给字符串。 This is wierd! 这太奇怪了!

This is because you are calling the Unicode version of RegQueryValueEx() , so the string is returned in Unicode (UTF-16). 这是因为您正在调用Unicode版本的RegQueryValueEx() ,所以该字符串以Unicode(UTF-16)返回。

You will have to use wide character parameters to get the value. 您将必须使用宽字符参数来获取值。

Change this line: 更改此行:

char value[256] = "\0";

To use wchar_t instead. 改为使用wchar_t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM