C++ - getting null values in value read from registry

假装没事ソ 提交于 2020-01-11 11:29:28

问题


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. This is wierd!


回答1:


You have built targeting Unicode and so the registry API is returning UTF-16 Unicode text. Instead of char use wchar_t and remember that each wchar_t element is 2 bytes wide.

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.




回答2:


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. This is wierd!

This is because you are calling the Unicode version of RegQueryValueEx(), so the string is returned in 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.



来源:https://stackoverflow.com/questions/34841080/c-getting-null-values-in-value-read-from-registry

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!