能否使用Windows API的ANSI函数处理UTF-8字符串呢?
比如说,如果我有一个用UTF-8编码的路径,我可以调用CreateDirectoryA
或者CreateFileA
函数并传入UTF-8路径吗?还是在调用这些函数之前需要进行一些转换呢?
经过证实,已被接受的答案不再准确(截至Windows版本1903(2019年5月更新))。
现在应用程序可以将进程的活动代码页设置为UTF-8。这允许...A
函数(和CP_ACP
)与UTF-8一起使用。执行此操作的清单如下所示
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity type="win32" name="..." version="6.0.0.0"/>
<application>
<windowsSettings>
<activeCodePage xmlns="http://schemas.microsoft.com/SMI/2019/WindowsSettings">UTF-8</activeCodePage>
</windowsSettings>
</application>
</assembly>
来源和额外信息:使用 Windows UTF-8 代码页
不要使用其他方法,直接使用MultiByteToWideChar
将UTF-8转换为UTF-16编码,然后再调用宽字节API,如CreateDirectoryW
或CreateFileW
。
CreateDirectoryW(
CA2W( utf8Name, CP_UTF8 ) // convert from UTF-8 to UTF-16
... // other stuff
);
CreateDirectory(
CA2W( utf8Name, CP_UTF8 ) // convert from UTF-8 to UTF-16
... // other stuff
);
char
的字符串而不是基于wchar_t
的字符串。如果Windows完全支持UTF-8,那么您就可以在整个程序中直接使用UTF-8,而无需一直在UTF-8和UTF-16之间进行转换。 - dan04