How to covert CString to TCHAR and CString to LPCWSTR?
-
If you need to copy a CString object to an array of TCHAR you could do:
// assume strText is your CString ... TCHAR *czArray = NULL; // allocate character array czArray = new TCHAR[strText.GetLength() + 1]; _tcscpy(czArray, (LPCTSTR)strText); // DO WHATEVERR // Cleanup delete [] czArray;
The CString object has the LPCTSTR operator cast, so you can just cast your CString object to a LPCWSTR (LPCSTR if not unicode). Note that this is used in the above example for the _tcscpy function For further reading, have a look at the strings section of Codeproject, there are a few good articles that is a must-read.
"..Even my comments have bugs!"
Inspired by Toni78 -
the easy way:
USES_CONVERSION; CString Str(_T("This is my string")); // explicit copy as single byte chars (LCPSTR) char charBuf[255]; strcpy( charbuf, T2CA(Str) ); // explicit copy as wide chars (LPCWSTR) wchar_t wcharBuf[255]; wsccpy( wcharBuf, T2CW(Str) ); // generic TCHAR copy (LPCTSTR) TCHAR tcharBuf[255]; _tcscpy( tcharBuf, Str );
this works in UNICODE and non-UNICODE.~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Peter Weyzen Staff Engineer Santa Cruz Networks