Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VC++: how-to convert CString to TCHAR*

Tags:

visual-c++

mfc

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

like image 492
abhi312 Avatar asked Mar 15 '23 23:03

abhi312


1 Answers

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.

like image 195
Barmak Shemirani Avatar answered Mar 27 '23 03:03

Barmak Shemirani