Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

converting wchar_t * to const wchar_t *

1,157 views
Skip to first unread message

Sean Farrow

unread,
Jul 6, 2008, 12:48:40 PM7/6/08
to
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.


Thomas Maeder [TeamB]

unread,
Jul 6, 2008, 1:17:58 PM7/6/08
to
"Sean Farrow" <sean....@seanfarrow.co.uk> writes:

> 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.


> 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
}

Remy Lebeau (TeamB)

unread,
Jul 7, 2008, 12:48:28 PM7/7/08
to

"Sean Farrow" <sean....@seanfarrow.co.uk> wrote in message
news:4870f768$1...@newsgroups.borland.com...

> 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.

> 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


0 new messages