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…
[sourcecode language=’cpp’]CString Str;
LPCTSTR lpctszStr = Str;[/sourcecode]
The compiler replaces above line with a call to operator LPCTSTR(). So will look somewhat like this…
[sourcecode language=’cpp’]LPCTSTR lpctszStr = Str.operator LPCTSTR();[/sourcecode]
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.
[sourcecode language=’cpp’]LPTSTR lptszStr = Str.GetBuffer(0);
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.
[sourcecode language=’cpp’]CString rString;
int nLen = ::GetWindowTextLength(m_hWnd);
::GetWindowText(m_hWnd, rString.GetBufferSetLength(nLen), nLen+1);