Home > MFC > Converting CString to LPCTSTR or LPTSTR

Converting CString to LPCTSTR or LPTSTR

Converting from CString to char* is conditional, becuase CString is a TCHAR based implementation. TCHAR is defined as a char if _UNICODE is not defined, so if this is the case we can convert to char*, since TCHAR* and char*  are equal, else we’ve got to use function like MultiByteToWideChar/W2A/W2AEX etc.

So from now on for this post I will be using TCHAR version of char. Above explanation would have helped you in understanding what exactly is a TCHAR.

Converting CString to LPCTSTR –

CString has an inbuilt operator which returns a constant pointer to it’s internal data member. It’s called operator LPCTSTR().

So if you write code like this…

CString Str;
LPCTSTR lpctszStr = Str;

The compiler replaces above line with a call to operator LPCTSTR(). So will look somewhat like this…

LPCTSTR lpctszStr = Str.operator LPCTSTR();

This is the reason why we can directly pass CString objects to SDK functions which takes LPCTSTR arguments, for e.g. ::SetWindowText.

Converting CString to LPTSTR –

Converting from CString to LPTSTR is slightly bit more work. We’ve got to call function GetBuffer to get internal data pointer. Don’t forget to call ReleaseBuffer once you are done with the buffer.

LPTSTR lptszStr = Str.GetBuffer(0);
Str.ReleaseBuffer();

A different flavor of this function exists called GetBufferSetLength. Well what’s the use of this function, you can explicitly as CString to give you a larger buffer that the current one. For eg. if you wanna call the SDK version of GetWindowText using a CString object without using a temporary raw TCHAR buffer, you can use GetBufferSetLength function passing the required buffer length as the argument and of course the ReleaseBuffer call should be made too!

Here is a classic example from CWnd::GetWindowText on how to use GetBufferSetLength.

CString rString;
int nLen = ::GetWindowTextLength(m_hWnd);
::GetWindowText(m_hWnd, rString.GetBufferSetLength(nLen),  nLen+1);
rString.ReleaseBuffer();

Converting to and from a unicode string –

https://nibuthomas.wordpress.com/2008/07/02/how-to-convert-a-ansi-string-to-unicode-string-and-vice-versa/

  1. Alberto Chavez
    November 19, 2020 at 5:14 am

    muchas gracias, me salvaste!!

  2. Newlog
    February 5, 2010 at 4:47 pm

    Muy buena explicación!

  1. No trackbacks yet.

Leave a comment