0

I know that converting CByteArray to CString is pretty straightforward. But how do I do it the other way around - from CString to CByteArray?

default
  • 11,485
  • 9
  • 66
  • 102
Owen
  • 4,063
  • 17
  • 58
  • 78

2 Answers2

4

GetBuffer() method of the CString class returns the array you need. After that you can copy it using the memcpy or other similar function to a CByteArray object.

CString csData = L"someData";
CByteArray byteArr;

BYTE *pByteArray = (PBYTE)(LPCTSTR)csData.GetBuffer();
byteArr.SetSize(csData.GetLength());

memcpy(byteArr.GetData(), pByteArray, csData.GetLength());
Aurora
  • 53
  • 5
3

You need to take into account, that 1 character in a CString is usually not 1 byte.

const size_t noBytes = sizeof(CString::XCHAR) * myString.GetLength();
byteArray.SetSize( noBytes );
std::memcpy( 
    byteArray.GetData(),
    reinterpret_cast<BYTE*>(myString.GetBuffer()), 
    noBytes );

So you need to consider if this is really the intended behaviour.

tesuji
  • 56
  • 2