Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string to LPBYTE and RegEnumValueA

What is the proper way to cast std::string to LPBYTE to make this code work?

string Name;
string Value;
RegEnumValueA(hKey, 0, const_cast<char*>(Name.c_str()), &dwSize, NULL, NULL, (LPBYTE)const_cast<char*>(Value.c_str()), &dwSize2);

When I try to user this code everythins is okey with the string name, but there's a bad pointer error in the string value

like image 798
spandei Avatar asked Jun 04 '26 04:06

spandei


2 Answers

The proper way od getting std::string with data you want

//alloc buffers on stack
char buff1[1024];
char buff2[1024];

//prepare size variables
DWORD size1=sizeof(buff1);
DWORD size2=sizeof(buff2);

//call
RegEnumValueA(hKey, 0, buff1, &size1, NULL, NULL, (LPBYTE)buff2, &size2);

//"cast" to std::string
std::string Name(buff1);
std::string Value(buff2);
like image 72
peper0 Avatar answered Jun 05 '26 18:06

peper0


The pointer parameters should point to valid buffers that will be modified by a function. The c_str() of an unitialized string does not point to anything valid.

Use char buffers instead of a strings. This is a very good case of const_cast<> being totally uncalled for.

char Name[200], Value[200]; //Sizes are arbitrary
DWORD dwSize = sizeof(Name), dwSize2 = sizeof(Value);

RegEnumValueA(hKey, 0, Name, &dwSize, NULL, NULL, (LPBYTE)Value, &dwSize2);
like image 34
Seva Alekseyev Avatar answered Jun 05 '26 16:06

Seva Alekseyev