Hello !
This is a simple process. Visual Studio .NET (and ATL-MFC version 7)
supports new conversion macros with the following syntax:
C<sourcetype>2<constant><destination type><ex>
In which, <sourcetype> is T for generic text, A for ANSI, W for wchar_t
types and OLE for COM/BSTR strings (wchar_t normally). <constant> is a 'C'
if the destination pointer must be a constant one, and <destination type> is
the target type, again from the above list of source types. <ex> is 'EX' if
the target string's length needs to be defined in the template.
Thus, converting from CString to LPCWSTR is as simple as this:
CT2CW( (LPCTSTR) MyStringObj );
You could read this like "convert generic type to constant wchar_t".
Creating sentences like this helps you quickly understand how to build the
macro to support a specific conversion. The conversion is actually a class
that uses a certain piece of memory to hold a copy of the string in the
appropriate format. Thus, when the class goes out-of-scope, the new string
is freed. Generally, you should not rely on this, but use the conversion
macro as a parameter to a function or source of a string copying routine.
This allows you to create local strings that last just as long as you want
them to. The conversion should be used with "in-place conversion from one
pointer type to other" -mantra.
Following this idea, this piece of code is BAD, DO NOT USE:
LPCWSTR lpwStr = CT2CW( (LPCTSTR) StringObj );
Instead, something like this is much better, if the string is no longer than
20 characters
wchar_t string[20];
wcscpy( string, CT2CW( (LPCTSTR) StringObj );
If you don't have ATL-MFC v7, you can use the old-style conversion macros,
such as
T2CW( (LPCTSTR) StringObj );
Note that these macros MUST be used in the above mentioned string copying
way. Using them otherwise will have undesirable results.
See MSDN with "ATL and MFC String Conversion Macros" for more information on
the conversion routines. Same topic will cover the old-style conversion
macros.
-Antti Keskinen
"Paul" <Pa**@discussions.microsoft.com> wrote in message
news:76**********************************@microsof t.com...
Hi,
Any one knows how to convert CString to LPCWSTR?
Please advice, thanks!
-P