我注意到有两个编译器
Visual Studio 编译器中的标志(例如
C++)称为 MBCS 和 UNICODE。什么是
他们之间的区别?
Windows API 中的许多函数有两个版本: 一种需要char
参数(在特定于区域设置的代码页中)和一个需要wchar_t
参数(UTF-16 格式)。
int MessageBoxA(HWND hWnd, const char* lpText, const char* lpCaption, unsigned int uType);
int MessageBoxW(HWND hWnd, const wchar_t* lpText, const wchar_t* lpCaption, unsigned int uType);
这些函数对中的每一个都有一个不带后缀的宏,这取决于是否UNICODE
宏已定义。
#ifdef UNICODE
#define MessageBox MessageBoxW
#else
#define MessageBox MessageBoxA
#endif
为了使这项工作顺利进行,TCHAR
type 被定义为抽象 API 函数使用的字符类型。
#ifdef UNICODE
typedef wchar_t TCHAR;
#else
typedef char TCHAR;
#endif
然而,这是个坏主意。您应该始终明确指定字符类型。
我不明白的是 UTF-8 是怎样的
在概念上与 MBCS 不同
编码?
MBCS 代表“多字节字符集”。对于字面意义上的人来说,UTF-8 似乎符合条件。
But in Windows, "MBCS" only refers to character encodings that can be used with the "A" versions of the Windows API functions. This includes code pages 932 (Shift_JIS), 936 (GBK), 949 (KS_C_5601-1987), and 950 (Big5), but NOT UTF-8.
To use UTF-8, you have to convert the string to UTF-16 using MultiByteToWideChar
, call the "W" version of the function, and call WideCharToMultiByte
on the output. This is essentially what the "A" functions actually do, which makes me wonder why Windows doesn't just support UTF-8.
This inability to support the most common character encoding makes the "A" version of the Windows API useless. Therefore, you should always use the "W" functions.
Update:从 Windows 10 build 1903(2019 年 5 月更新)开始,现在支持 UTF-8 作为“ANSI”代码页。因此,我最初(2010 年)建议始终使用“W”函数不再适用,除非您需要支持旧版本的 Windows。看UTF-8 无处不在获取文本处理建议。
Unicode 是一种 16 位字符编码
这否定了我读到的有关
统一码。
MSDN 是错误的。 Unicode 是一种 21 位编码字符集,有多种编码,最常见的是 UTF-8、UTF-16 和 UTF-32。 (还有其他 Unicode 编码,例如 GB18030、UTF-7 和 UTF-EBCDIC。)
每当 Microsoft 提到“Unicode”时,它们实际上指的是 UTF-16(或 UCS-2)。这是有历史原因的。 Windows NT 是 Unicode 的早期采用者,当时 16 位被认为对每个人来说都足够了,而 UTF-8 仅在 Plan 9 上使用。所以 UCS-2was统一码。