d d
d d

Reputation: 181

RegSetValueEx function writing gibberish

I am using the RegSetValueEX in the following code and it is setting the value to incomprehensible chars (chinese looking). I'm guessing something with the whole beautiful world of encoding?

HKEY regKey;
std::string newIP = "192.168.1.2";

Result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("Comm\\VMINI1\\Parms\\TcpIp"), 0, 0, &regKey);
if (Result == ERROR_SUCCESS)
{
    Result = RegSetValueEx(regKey, TEXT("IPAddress"), 0, REG_SZ, (const BYTE*)newIP.c_str(), newIP.size() + 1);
    if (Result == ERROR_SUCCESS)
    {
        std::cout << "Done!";
    }
}

When I look at the registry entry however, the ip address is not set to the value supplied, it is random characters. What could be the problem?

Upvotes: 3

Views: 8249

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 597101

std::string uses char only. Most Win32 API functions, including RegOpenKeyEx() and RegSetValueEx(), use TCHAR instead (as evident by your use of the TEXT() macro). TCHAR maps to either char or wchar_t, and RegSetValueEx() maps to either RegSetValueExA() (Ansi) or RegSetValueExW() (Unicode), depending on whether the app is being compiled for Unicode or not.

In your case, I suspect that the app is being compiled for Unicode, so your data is mismatching what RegSetValueEx() is expecting.

Since you are working with char data, you should change your code to call RegSetValueExA() directly instead so there is no mismatch:

std::string newIP = "192.168.1.2";

Result = RegSetValueExA(regKey, "IPAddress", 0, REG_SZ, (const BYTE*)newIP.c_str(), newIP.length() + 1);

Otherwise, change your code to use std::wstring and RegSetValueExW() instead:

std::wstring newIP = L"192.168.1.2";

Result = RegSetValueExW(regKey, L"IPAddress", 0, REG_SZ, (const BYTE*)newIP.c_str(), (newIP.length() + 1) * sizeof(wchar_t));

Upvotes: 5

Steve
Steve

Reputation: 7271

You are using std::string which is ANSI, but you're probably compiling with UNICODE defined. This means that you RegSetValueEx will actually be calling RegSetValueExW (the unicode version).

HKEY regKey;
std::wstring newIP = TEXT("192.168.1.2");     // Use a wide string

Result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("Comm\\VMINI1\\Parms\\TcpIp"), 0, 0, &regKey);
if (Result == ERROR_SUCCESS)
{
    Result = RegSetValueEx( regKey, 
        TEXT("IPAddress"), 
        0, 
        REG_SZ, 
        (const BYTE*)newIP.c_str(), 
        ( newIP.size() + 1 ) * sizeof( wchar_t ) );    // note the size change
    if (Result == ERROR_SUCCESS)
    {
        std::cout << "Done!";
    }
}

Upvotes: 3

Related Questions