abhi312
abhi312

Reputation: 362

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

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

Upvotes: 4

Views: 15656

Answers (2)

Barmak Shemirani
Barmak Shemirani

Reputation: 31599

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.

Upvotes: 5

IInspectable
IInspectable

Reputation: 51413

This depends on why you need a non-const TCHAR*. There are two main scenarios:

  1. Manual update of the contents of a CString object:

    In that case you will have to call CSimpleStringT::GetBuffer (specifying the minimal length of the final string), update the contents, and call CSimpleStringT::ReleaseBuffer. Calling ReleaseBuffer is mandatory, as it updates internal state. Failure to call ReleaseBuffer can lead to the string exposing unexpected behavior.

  2. Failure to expose const-correctness at an interface:

    If this is the case you can either update the interface to take a const TCHAR* instead of a TCHAR*, and invoke CSimpleStringT::operator PCXSTR by passing the CString object.
    If you cannot update the interface, you are best advised to make a copy into a TCHAR array and pass a pointer to this copy.
    If you can make sure that the implementation will not ever modify the contents referenced through the TCHAR* parameter, you could use a const_cast instead. This is not recommended, as it can introduce bugs in the future, by modifying unrelated code.

Upvotes: 2

Related Questions