0
votes

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﵄﷽꯽ꮫꮫ"
1
Possible duplicate of LPCSTR, LPCTSTR and LPTSTR - Max Vollmer
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 instead. - IInspectable
What are you actually trying to achieve? This looks a bit like an XY problem. - Jabberwocky

1 Answers

1
votes

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.