views:

337

answers:

2

I need to convert CString to BYTE array. I don't know why, but everything that I found in internet does not work :( For example, I have

CString str = _T("string");

I've been trying so 1)

BYTE *pbBuffer = (BYTE*)(LPCTSTR)str;

2)

BYTE *pbBuffer = new BYTE[str.GetLength()+1];
memcpy(pbBuffer, (VOID*)(LPCTSTR)StrRegID, str.GetLength());

3)

BYTE *pbBuffer = (BYTE*)str.GetString();

And always pbBuffer contains just first letter of str

DWORD dwBufferLen = strlen((char *)pbBuffer)+1;

is 2

But if I use const string:

BYTE *pbBuffer = (BYTE*)"string";

pbBuffer contains whole string

Where is my mistake?

+2  A: 

Your CString is Unicode (two bytes per character) and you try to interpret it as ANSI (one byte per character). This leads to results you don't expect.

Instead of casting the underlying buffer into char* you need to convert the data. Use WideCharToMultiByte() for that.

sharptooth
A: 

You are probably compiling with unicode. This means that your CString contains wchar_t instead of char. Converting a wchar_t pointer to a char pointer causes you to interpret the second byte of the first wchar_t as a string terminator (since that by is 0 for the most common characters)

When using visual studio you should always use _T() to declare string literals and TCHAR as your character type. In your case:

BYTE* pBuffer = (BYTE*)(LPCTSTR)str;

You get the buffer, but every other byte is most probably zero.

Use a CStringA if you need an ANSI string. (But then skip the _T() when initializing it)

yngvedh