convert std::string to const BYTE* for RegSetValueEx()

后端 未结 4 1018
深忆病人
深忆病人 2021-01-19 07:54

I have a function that gets a std::string. That function calls

RegSetValueEx

the 5th parameter is the value of the registry value and expects a variable of t

4条回答
  •  春和景丽
    2021-01-19 08:27

    void function(const std::string& newValue)
    {
        HKEY keyHandle;
        if(RegOpenKeyEx(HKEY_CLASSES_ROOT, TEXT("some key"),0,KEY_ALL_ACCESS,&keyHandle) == ERROR_SUCCESS)
        {
    
            if (RegSetValueExA(keyHandle, "some value", NULL, REG_SZ, (const BYTE*)newValue.c_str(), newValue.size() + 1)==ERROR_SUCCESS)
            {
                    //do something
            }
            RegCloseKey(keyHandle);
        }
    }
    

    I removed the part where you convert your string to a wstring, instead you'll be using the ANSI version of RegSetValueEx explicitly.

    quote from RegSetValueEx remarks in MSDN:

    If dwType is the REG_SZ, REG_MULTI_SZ, or REG_EXPAND_SZ type and the ANSI version of this function is used (either by explicitly calling RegSetValueExA or by not defining UNICODE before including the Windows.h file), the data pointed to by the lpData parameter must be an ANSI character string. The string is converted to Unicode before it is stored in the registry.

    Also note that the cbData parameter should include the size of the null termination aswell.

提交回复
热议问题