0

I'm creating a NPAPI dll file and I need to get some information from the registry, but when I use RegQueryValueEx, I get some strange characters.

For instance, my computer model is "N310", but I get "Nfb1fb1" or "N$(".

I'm pretty sure that it's a charset issue, but I'm new with C++ and I need some help.

I'm using Visual Studio 2010 and my project is using the UNICODE charset.

Here is my code:

char lszValue[255];
std::string cadena;
HKEY hKey;
LONG returnStatus;
DWORD dwType=REG_SZ;
DWORD dwSize=255;

returnStatus = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\BIOS", NULL, KEY_READ, &hKey);
if (returnStatus == ERROR_SUCCESS) {
    returnStatus = RegQueryValueEx(hKey, L"SystemProductName", NULL, &dwType,(LPBYTE)&lszValue, &dwSize);
    lszValue[dwSize] = 0;
    cadena.assign(lszValue, dwSize);

    return cadena;
}

Thank you very much and thanks for advance.

user461054
  • 41
  • 2
  • 4
  • I wouldn't hard-code `dwSize=255`, that's fragile. You could use an [array size helper](http://stackoverflow.com/a/4064220/168225) or `std::array` instead. – Georg Fritzsche Aug 09 '12 at 07:53

1 Answers1

3

If your project uses UNICODE charset, then probably all WINAPI functions are bound to unicode strings, that is, RegQueryValueEx is actually RegQueryValueExW that takes wchar_t array, not char array.

When using non-Unicode, single-byte projects, the function would be RegQueryValueExA and it would work with char[].

To make your project (non)unicode-safe, use TCHAR macro instead of char. try this code:

DWORD const dwSize=255;
TCHAR lszValue[dwSize];
std::wstring cadena;

HKEY hKey;
LONG returnStatus;
DWORD dwType=REG_SZ;
returnStatus = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\BIOS", NULL, KEY_READ, &hKey);
if (returnStatus == ERROR_SUCCESS)
{
    returnStatus = RegQueryValueEx(hKey, L"SystemProductName", NULL, &dwType, (LPBYTE)&lszValue, &dwSize);
    lszValue[dwSize] = 0;
    cadena.assign(lszValue, dwSize);

    return cadena;
}

I've changed just the types. There may be other errors/typos. Just remember that std::wstring is for wchar_t

quetzalcoatl
  • 32,194
  • 8
  • 68
  • 107