spandei
spandei

Reputation: 229

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

Upvotes: 3

Views: 2845

Answers (3)

peper0
peper0

Reputation: 3223

If you really want to "cast" std::string as you said, you could consider the following piece of code. It should work on any std::string implementation I know, but still it is a bit "hacky" and I'd not recommend it.

string Name(1024, ' ');
string Value(1024, ' ');
DWORD dwSize=Name.size();
DWORD dwSize2=Value.size();

RegEnumValueA(hKey, 0, const_cast<char*>(&Name[0]), &dwSize, NULL, NULL, (LPBYTE)const_cast<char*>(&Value[0]), &dwSize2);

Upvotes: 0

peper0
peper0

Reputation: 3223

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);

Upvotes: 1

Seva Alekseyev
Seva Alekseyev

Reputation: 61378

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);

Upvotes: 1

Related Questions