Reputation: 47
My code is setting 1 char of the registry name and value.
bool setRegValue(std::wstring valueName, std::wstring valueToSet)
{
HKEY key=NULL;
if (get_HKEY_LOCAL_MACHINE(&key) && (key!=NULL))
{
if (RegSetValueEx((HKEY)key, (LPCSTR)valueName.c_str(), 0, REG_SZ, (const BYTE*)valueToSet.c_str(), (valueToSet.size() +1)*sizeof(wchar_t)) != ERROR_SUCCESS)
{
RegCloseKey((HKEY)key);
log.error("Failed to SET the registry value. Name : "+ std::string(valueName.begin(), valueName.end())+" Value : "+ std::string(valueToSet.begin(), valueToSet.end()));
RegCloseKey(key);
return false;
}
log.info("Successfully SET the registry value. Name : " + std::string(valueName.begin(), valueName.end()) + " Value : " + std::string(valueToSet.begin(), valueToSet.end()));
RegCloseKey(key);
return true;
}
return false;
}
And, this is the calling method.
bool setServiceAsClient()
{
if (setRegValue(L"ServiceType", L"Client"))
return true;
return false;
}
Its setting the registry name as S
And, value as C
Upvotes: 1
Views: 79
Reputation: 85452
When a wide-char string is seen as a 1-char string, that's a symptom that you're providing a wide-char string where a multi-byte string is expected.
Indeed we see the error here: (LPCSTR)valueName.c_str()
(where valueName
is a std::wstring
).
LPCSTR
is const char *
, whereas wstring::c_str()
returns const wchar_t *
.
So L"ServiceType"
is seen as "S\0e\0r\0v\0i\0c\0e\0T\0y\0p\0e\0"
, which becomes simply "S"
There are 2 solutions possible:
std::string
instead of std::wstring
(and remove the L
from strings like L"ServiceType"
). This solution is not recommended, since the Win32 API internally is Unicode.LPCSTR
(if you do need to cast, use LPTSTR
instead, which always matches project character set settings).See Working with Strings - Win32 API for more details.
Upvotes: 1