简体   繁体   English

Windows API ANSI函数和UTF-8

[英]Windows API ANSI functions and UTF-8

Is it possible to use Windows API ANSI functions with UTF-8 strings? 是否可以使用带有UTF-8字符串的Windows API ANSI函数?

For example, say I have a path encoded in UTF-8. 例如,假设我有一个以UTF-8编码的路径。 Can I call CreateDirectoryA or CreateFileA and use a UTF-8 path, or do I have to perform some conversion before calling the functions? 我可以调用CreateDirectoryACreateFileA并使用UTF-8路径,还是在调用函数之前必须执行一些转换?

MultiByteToWideChar 。使用MultiByteToWideChar将UTF-8转换为UTF-16,然后调用宽字符API,如CreateDirectoryWCreateFileW

An easier approach (than using raw Win32 API MultiByteToWideChar) would be to use ATL conversion helpers , like CA2CW . 一种比使用原始Win32 API MultiByteToWideChar更简单的方法是使用ATL转换助手 ,如CA2CW You can specify CP_UTF8 as code page (second parameter in the constructor), to convert from Unicode UTF-8 to Unicode UTF-16: 您可以将CP_UTF8指定为代码页(构造函数中的第二个参数),以便将Unicode UTF-8转换为Unicode UTF-16:

CreateDirectoryW( 
  CA2W( utf8Name, CP_UTF8 ) // convert from UTF-8 to UTF-16
  ... // other stuff
);

Note that in Unicode builds (which should be the default ones these days), CreateDirectory just expands to CreateDirectoryW, so I would just drop the ending "W" and use the (IMHO, more readable) CreateDirectory: 请注意,在Unicode构建中(这些天应该是默认构建),CreateDirectory只是扩展到CreateDirectoryW,所以我只需删除结尾“W”并使用(恕我直言,更易读)CreateDirectory:

CreateDirectory( 
  CA2W( utf8Name, CP_UTF8 ) // convert from UTF-8 to UTF-16
  ... // other stuff
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM