Re: std::string and RegQueryValueEx
David Wilkinson schrieb:
L.Allan wrote:
I've mostly use CString and CWinApp::GetProfileString to get string
data from the registry. Now I want to use the native Win32Api
RegQueryValueEx for a string that can range from 500 to 30000 bytes long.
I was considering replacing the use of
CString myRegString
with
std::String myRegString
and wondering about the correct calls.
You can't use std::string and remain unicode aware. Today, I would say using
char strings is a bug. Always use TCHAR or wchar_t as character type.
If you really need std::basic_strings, then instanciate create your own string
class:
typedef std::basic_string<TCHAR> tstring;
However, usually you should stick to CString in MFC applications.
My impression is that when the MFC GetProfileString uses a CString, it
knows how to get the CString to be the appropriate length. Do I need
to use the std::string.reserve before doing this with RegQueryValueEx?
Is the following the appropriate sequence?
RegOpenKeyEx(HKEY_CURRENT_USER,
"Software\\MyCompay\\MyApp\\Settings",
0, KEY_ALL_ACCESS, &hSubKey);
DWORD dwType;
DWORD dwLen = 30000;
std::string ssRegString;
ssRegString.reserve(30000);
RegQueryValueEx(hSubKey,
"ChapContents",
NULL,
&dwType,
(LPBYTE)ssRegString.c_str(),
&dwLen);
L.Allan:
It is not legal to use std::string in this way.
The buffer returned from std::string::c_str() is const, and in any case
is not guaranteed to be related to the internal representation of the
string (which might not use a contiguous char array).
If you want std::string, I would just do something like
DWORD dwType;
DWORD dwLen = 30000;
BYTE value[30000];
This is very bad coding style and will silently fail once the returned data is
longer than 30000 bytes. And if it is shorter, its a waste of resources.
You should query how much data you need, and allocate that dynamically.
CString can handle this much better.
And how about unicode?
RegQueryValueEx(hSubKey,
"ChapContents",
NULL,
&dwType,
value,
&dwLen);
std::string ssRegString((const char*)value);
Unneccessary type cast.
Norbert