VC ++: how to convert CString to TCHAR *

VC ++: how to convert a CString value to TCHAR *. One method is the GetBuffer (..) function. Is there any other way to convert CString to TCHAR *.

+4
source share
2 answers

CString::GetBuffer() does not do any conversion, it gives direct access to the string.

To make a copy CString:

TCHAR* buf = _tcsdup(str);
free(buf);

or

TCHAR* buf = new TCHAR[str.GetLength() + 1];
_tcscpy_s(buf, str.GetLength() + 1, str);
delete[]buf;

However, the above code is usually not useful. You can change it like this:

TCHAR buf[300];
_tcscpy_s(buf, TEXT("text"));

Usually you need to read data in a buffer, so you want to make the buffer size larger than the current one.

Or you can just use it CString::GetBuffer(), again you may want to increase the size of the buffer.

GetWindowText(hwnd, str.GetBuffer(300), 300);
str.ReleaseBuffer(); //release immediately
TRACE(TEXT("%s\n"), str);

Other times you only need const cast const TCHAR* cstr = str;

, TCHAR . ANSI, unicode, . .

+5

, TCHAR*. :

+2

All Articles