Are there any problems?
There are a few questions:
CString is a template specialization of CStringT . Depending on the BaseType that describes the character type, there are two specific specializations: CStringA (using char ) and CStringW (using wchar_t ).- Although
wchar_t is commonly used on Windows to store UTF-16 encoded units, the use of char is ambiguous. The latter usually stores ANSI encoded characters, but can also store ASCII, UTF-8, or even binary data. - We do not know the character encoding (or even the character type) of the
CString (which is controlled by the _UNICODE preprocessor _UNICODE ), which makes the question ambiguous. We also do not know the desired character encoding std::string . - The conversion between Unicode and ANSI is inherently lossy: ANSI encoding can only represent a subset of the Unicode character set.
To solve these problems, I assume that wchar_t will store UTF-16 encoded units, and char will contain UTF-8 octet sequences. This is the only reasonable choice you can make to ensure that the source and destination strings retain the same information without restricting the solution to a subset of the source or destination domains.
The following implementations convert the conversion between CStringA / CStringW and std::wstring / std::string from UTF-8 to UTF-16 and vice versa:
#include <string> #include <atlconv.h> std::string to_utf8(CStringW const& src_utf16) { return { CW2A(src_utf16.GetString(), CP_UTF8).m_psz }; } std::wstring to_utf16(CStringA const& src_utf8) { return { CA2W(src_utf8.GetString(), CP_UTF8).m_psz }; }
The remaining two functions create C ++ string objects from MFC strings, leaving the encoding unchanged. Please note that although previous functions cannot handle the built-in NUL characters, these functions are protected from this.
#include <string> #include <atlconv.h> std::string to_std_string(CStringA const& src) { return { src.GetString(), src.GetString() + src.GetLength() }; } std::wstring to_std_wstring(CStringW const& src) { return { src.GetString(), src.GetString() + src.GetLength() }; }
IInspectable Sep 06 '18 at 10:07 2018-09-06 10:07
source share