Board index » cppbuilder » converting wchar_t * to const wchar_t *

converting wchar_t * to const wchar_t *


2008-07-07 12:48:40 AM
cppbuilder97
How can I convert wchar_t * to const wchar_t *?
I'm trying to use the MultiByteToWideChar function with an std::wstring as
the output string.
Any help aprediated.
The line of code is:
MultiByteToWideChar(CP_ACP, 0, __FUNC__, -1,DragonInfo.FunctionName.c_str(),
DragonInfo.FunctionName.size());
Chers
Sean.
 
 

Re:converting wchar_t * to const wchar_t *

"Sean Farrow" < XXXX@XXXXX.COM >writes:
Quote
How can I convert wchar_t * to const wchar_t *?
Conversion from 'pointer to non-const' to 'pointer to const' are done
by the compiler does implicitly.
Quote
I'm trying to use the MultiByteToWideChar function with an std::wstring as
the output string.
Any help aprediated.
The line of code is:
MultiByteToWideChar(CP_ACP, 0, __FUNC__, -1,DragonInfo.FunctionName.c_str(),
DragonInfo.FunctionName.size());
Hmm. This asks for the conversion opposite to the one you write in the
Subject: header and further above, i.e. from 'pointer to const' to
'pointer to non-const'.
If safe, this can be done using the const_cast operator, but in this
case, the conversion would be very unsafe.
The docs of MultiByteToWideChar() indicate to first call it with 0
passed as 5th and 6th parameter. The return value is the required size
of the wide character buffer to hold the result of the conversion. You
can then use that value to create a wide character buffer of that size
and call MultiByteToWideChar() again, this time with non-0 values
passed as 5th and 6th parameter.
E.g.:
int const bufferSize(MultiByteToWideChar(CP_ACP,
0,
__FUNC__,-1,
0,0));
if (bufferSize==0)
; // error handling
else
{
std::vector<wchar_t>wchars(bufferSize);
int const nrConverted(MultiByteToWideChar(CP_ACP,
0,
__FUNC__,-1,
&wchars[0],nrOfWideChars);
if (nrConverted==0)
; // error handling
else
; // use wchars
}
 

Re:converting wchar_t * to const wchar_t *

"Sean Farrow" < XXXX@XXXXX.COM >wrote in message
Quote
How can I convert wchar_t * to const wchar_t *?
I think you mean the other way around - how to convert a 'const wchar_t*' to
a 'wchar_t*'. The std::wstring::c_str() method returns a 'const' pointer
that you cannot write to.
Quote
I'm trying to use the MultiByteToWideChar function
with an std::wstring as the output string.
That won't work, for the reason mentioned above. You will have to use a
separate wchar_t[] buffer first, and then copy it to the std::wstring
afterwards, ie:
int len = ::MultiByteToWideChar(CP_ACP, 0, __FUNC__, -1, NULL, 0);
if( len>0 )
{
std::vector<wchar_t>buffer(len);
len = ::MultiByteToWideChar(CP_ACP, 0, __FUNC__, -1, &buffer[0],
len);
buffer[len] = L'\0';
DragonInfo.FunctionName = &buffer[0];
}
Gambit
 

{smallsort}