0

I have tried to convert a CString To BYTE*` and "BYTE* to CByteArray" in MFC, With Your Suggestions The CString Has Been Converted To BYTE*. But I'm not able to Convert The Entire Byte* To CByteArray It Returns Partial Data With Some Garbage Values. I Described My Actual Problem Here...

The code:

CString csData =_T("someData");

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

CString str;
str=LPTSTR(pByteArray);
AfxMessageBox(str); //returns "someData" 

CByteArray arrByte2;

arrByte2.SetSize(csData.GetLength()+1);

memcpy(arrByte2.GetData(), pByteArray, csData.GetLength()+1);

CString text((LPTSTR)arrByte2.GetData(),arrByte2.GetSize());
CStringA result(text);
AfxMessageBox(text);//returns "some﵄﷽꯽ꮫꮫ"
srinivasan
  • 99
  • 1
  • 4
  • Possible duplicate of [LPCSTR, LPCTSTR and LPTSTR](https://stackoverflow.com/questions/321413/lpcstr-lpctstr-and-lptstr) – Max Vollmer May 23 '18 at 07:24
  • You asked the wrong question. Clearly, you have no issues converting the controlled sequence of characters to a `BYTE*`. Your real issue is, that you later fail to **interpret** that data appropriately. Besides, `GetBuffer()` is the wrong call (for one, it requires that you call `ReleaseBuffer()` later on). What you meant to call is [GetString](https://learn.microsoft.com/en-us/cpp/atl-mfc-shared/reference/csimplestringt-class#getstring) instead. – IInspectable May 23 '18 at 10:09
  • 1
    What are you _actually_ trying to achieve? This looks a bit like an [XY problem](http://xyproblem.info). – Jabberwocky May 23 '18 at 13:33

1 Answers1

1

The problem is here:

str = (LPCSTR(pByteArray));

You cast pByteArray to a LPCSTR which is actually a const char *. But as your program is compiled as UNICODE program, CString is a string of wide characters (wChar_t) and pByteArray points to an array of wChar_t (wide characters, or 16 bit characters). Look at the memory pointed by pByteArray with the debugger.

So the memory pointed by pByteArray looks like this:

's', 0, 'o', 0, 'm', 0,  etc.
|-----|
^ this is one wide char     

and not like this as you expect:

's', 'o', 'm',   etc.

In order to correct, you need to cast to LPTSTR (as you're doing in the first part of the code snippet) and not to LPCSTR:

str = LPTSTR(pByteArray);

BTW the extra () around the expression are not necessary.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115