0

I have an Ansi char array like and want to initialize a CStringW (WCHAR specialization of CString template). But the CString object does not have copy the chars from the array.

CStringW sSample = "ABC";
int length = sSample.GetLength(); // returns 3
PCWSTR wcsSample = (PCWSTR)sSample;
wcout << (int)wcsSample[0];  // output: 0
  • Version: ATL/MFC version 8.0
  • Platform: Windows CE 5.0 (x86)

Do you see any workaround?

harper
  • 13,345
  • 8
  • 56
  • 105

1 Answers1

0

Well, I found the answer myself. It's a bug in the MFC method

CStringT& operator=( __in_z_opt PCYSTR pszSrc )

The method calculates the length of the required buffer and allocates the buffer. The calculation does not include the terminating null character. Thereafter it calls MultiByteToWideChar, passing the length as the cchWideChar parameter.

The function MultiByteToWideChar returns 0 as failure indication, but this is ignored by the MFC. As a side effect, MultiByteToWideChar fills the output buffer on some platforms like Win32 and Windows CE 5.0 (SH4).

But the Windows CE 5.0 (x86) does not fill the buffer. Although the allocated buffer is too small, the bug is not visible on most platforms but on Windows CE 5.0 (x86). Here you get an empty CString after the assignment.

The defect in the MFC is present in all MFC variants. But it is covered by a behavior of MultiByteToWideChar that behaves different on platforms.

harper
  • 13,345
  • 8
  • 56
  • 105