A
CString
is a sequence of
TCHAR
characters. A
TCHAR
is a
char
or a
wchar_t
depending on the project character set setting (ANSI/multi-byte or Unicode).
You can cast the pointer to the data in the
CString
to
BYTE*
:
const BYTE *pByte = reinterpret_cast<const BYTE*>(str.GetString());
Note that I have used C++ casting here and use
const
because the
CString::GetString()
return type is
LPCTSTR
. If you really need a non const pointer (want to modify the
CString
) you can use
CString::GetBuffer()
but then you have to call
CString::ReleaseBuffer()
afterwards.
If you have a Unicode build, the number of characters in the string is not identical to the number of bytes. You have to take that into account when copying to the byte array. Then there is also no need for a
BYTE*
pointer variable:
CByteArray arrByte2;
size_t byteSize = (str.GetLength() + 1) * sizeof (TCHAR);
arrByte2.SetSize(byteSize);
memcpy(arrByte2.GetData(), str.GetString(), byteSize);
Now the byte array contains all the bytes from the string including the terminating NULL bytes and can be assigned back to a
CString
:
CString text(reinterpret_cast<LPCTSTR>(arrByte2.GetData()), arrByte2.GetSize() / sizeof(TCHAR));
Note that the number of characters has to be calculated now by dividing by the size of a character. It would be also not necessary to have a terminating NULL byte in the array here because the
CString
constructors accepting a length parameter will append that.