2

I'm querying data from the registry and it's being outputted as LPBYTE, and this is where i'm stuck. I need to convert the LPBYTE into a type of data that I can manipulate such as a String.

This is my code so far

HKEY hk;
string poolID;
DWORD dwSize     = 0;
DWORD dwDataType = 0;
DWORD dwValue;
LPBYTE lpValue   = NULL;
CA2W registryLocation("Software\\Example");
// Check registry if exists, otherwise create.
LONG openReg = RegOpenKeyEx(HKEY_CURRENT_USER, registryLocation, 0, KEY_QUERY_VALUE, &hk);
if (openReg==ERROR_SUCCESS) {  } else { cout << "Error (Could not open/create Registry Location)\n"; }
// Get buffer size
LONG getRegBuf = RegQueryValueExA(hk, "", 0, &dwDataType, lpValue, &dwSize);
if (getRegBuf==ERROR_SUCCESS) { cout << "Got reg key buf size\n"; } else { cout << "Error (registry key does not exist)/n"; intro(); }
lpValue = (LPBYTE)malloc(dwSize);
// Open reg value
LONG getReg = RegQueryValueExA(hk, "", 0, &dwDataType, (LPBYTE)&dwValue, &dwSize);
if (getReg==ERROR_SUCCESS) { cout << "Successful\n"; } else { cout << "Error\n"; }
cout << dwValue;

Any help or code examples will be much appreciated.

Ryan
  • 957
  • 5
  • 16
  • 34
  • 1
    Allocate a char array and put it in there. So declare `lpValue` to be `char*`. You need to allow for the possibility that the data in the registry is not null terminated. – David Heffernan Dec 22 '12 at 22:03
  • I tried `char* regValue = (LPBYTE)lpValue;` however VS is reporting that a value of type LPBYTE can't be used with char *. – Ryan Dec 22 '12 at 22:16
  • Are you reading a DWORD or a buffer? – James Dec 22 '12 at 22:20
  • It makes no sense to cast a LBYTE to a LPBYTE. Use `char* regValue = (char*)lpValue;` instead. – harper Dec 22 '12 at 22:20

1 Answers1

3

You need to declare lpValue to be char*.

char* lpValue;

Then allocate it with a call to new.

lpValue = new char[dwSize+1];

Allocate an extra element in case the registry data is mal-formed and is missing a null-terminator. That is something that can happen. Then set the last element to \0:

lpValue[dwSize] = '\0';

Then get the value:

LONG getReg = RegQueryValueExA(..., (LPBYTE)&dwValue, ...);

Deallocate using delete[]:

delete[] lpValue;
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490