CW2A(LPCWSTR)str) 和 CW2A(LPCWSTR)str, CP_UTF8) 有什么区别?

What is difference between CW2A(LPCWSTR)str) and CW2A(LPCWSTR)str, CP_UTF8)?

我正在尝试将几个 CStringW 字符串转换为 CStringA 字符串。其中一个字符串(我们称之为 otherLangString)是其他语言(中文、阿拉伯语等)。像这样使用时,所有其他字符串都没有问题转换:

CW2A((LPCWSTR)some_String);

但是当用于 otherLangString 时,我得到的是“??????” 所以为了解决这个问题,我做了这个并且成功了

CW2A(some_String, CP_UTF8);

现在在代码中,除了一个看起来像第二个示例之外,所有转换看起来都像第一个示例。

为了保持一致性,我混合了以上两个并对所有人都这样做了。

CW2A((LPCWSTR)some_String, CP_UTF8);

我的问题是,following 和 following 有什么区别?

- CW2A((LPCWSTR)some_String, CP_UTF8) and CW2A(some_String, CP_UTF8);
- CW2A((LPCWSTR)some_String) and CW2A(some_String, CP_UTF8);

CW2ACW2AEX<>, and it's c'tor is documented 的类型定义。使用 2 个参数的 c'tor 允许您明确指定用于转换的代码页:

nCodePage:
The code page used to perform the conversion. See the code page parameter discussion for the Windows SDK function MultiByteToWideChar for more details.

如果您不指定代码页,则使用当前线程的 ANSI 代码页进行转换(您很少需要那样)。这在 ATL and MFC String Conversion Macros:

下解释

By default, the ATL conversion classes and macros will use the current thread's ANSI code page for the conversion. If you want to override that behavior for a specific conversion using macros based on the classes CA2WEX or CW2AEX, specify the code page as the second parameter to the constructor for the class.

在你的情况下,

CW2A((LPCWSTR)some_String);

使用线程的当前 ANSI 代码页从 UTF-16 转换为窄字符串。只有在使用相同的 ANSI 代码页进行解释时,结果才有意义。更糟糕的是,ANSI 代码页编码的字符串不能代表所有的 Unicode 字符。

另外一段代码

CW2A(some_String, CP_UTF8);

从 UTF-16 转换为 UTF-8。这通常是有利的,因为转换是无损且明确的。两种编码都可以表示同一组字符。编码后的字符串可以被任何能够解释 UTF-8 的 reader 解码。


注意:一般情况下,不能直接使用Windows中CStringA中存储的UTF-8编码的字符串。通过网络发送内容或将它们写入磁盘是安全的。但是如果你想将它传递给 Windows API (例如用于显示)你必须先转换为 UTF-16。 Windows API 的 ANSI 版本不支持 UTF-8。