VC++: how-to convert CString value to TCHAR*.One method is GetBuffer(..) function. Is there any other way we can convert CString to TCHAR*.
CString::GetBuffer()
doesn't make any conversion, it gives direct access to string.
To make a copy of 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 might want to modify it like so:
TCHAR buf[300];
_tcscpy_s(buf, TEXT("text"));
Usually you need to this to read data in to buffer, so you want to make the buffer size larger than the current size.
Or you can just use CString::GetBuffer()
, again you might want to make the buffer size bigger.
GetWindowText(hwnd, str.GetBuffer(300), 300);
str.ReleaseBuffer(); //release immediately
TRACE(TEXT("%s\n"), str);
In other cases you need only const cast const TCHAR* cstr = str;
Lastly, TCHAR
is not very useful. If your code is compatible with both ANSI and unicode then you might as well make it unicode only. But that's just a suggestion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With