如何将 wchar_t** 转换为 char**?
我得到 argv 作为 wchar_t** (见下文),因为我需要使用 unicode,但我需要将其转换为 char **。我怎样才能做到这一点?
int wmain(int argc, wchar_t** argv)
{
I get argv as wchar_t** (see below), because I need to work with unicode, but I need to convert it to char **. How can I do that?
int wmain(int argc, wchar_t** argv)
{
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有不止一种方法可以做到这一点。根据您的环境和可用的编译器/标准库/其他库,您至少有三种选择:
您真的需要进行转换吗?
您应该意识到,通常(尤其是在 Windows 上)从 wchar_t 字符串到 char 字符串的转换是有损转换。系统对字符串使用的字符集通常不是UTF-8。例如,如果您将带有国家字符或某些亚洲语言的文件名转换为字符字符串,您很可能会得到一些无法真正用于访问原始文件的内容。
There is more than one way to do this. Depending on your environment and available compiler/standard library/other libraries, you have at least three choices:
Do you really need to do the conversion?
You should realise that often (especially on Windows) the conversion from wchar_t string to char string is a lossy conversion. The character set used by system for char strings is often not UTF-8. E.g. if you convert a file name with national characters or in some Asian language to char string you are most likely going to get something that will not be really usable to access the original file.
这可以解决问题:
This does the trick:
为什么需要转换?在大多数情况下,您需要更改项目设置,因此所有内容都接受宽字符。如果第三方库需要非 Unicode 字符串,那么您需要使用适当的 Unicode 选项重新编译它。如果 Unicode 没有合适的选项,我会摆脱这个库并找到(编写)一个更好的库。
Why do you need to convert? In most of the cases you need to change your project settings, so everything accepts wide chars. If a third party library wants non-Unicode string, then you need to recompile it with the proper options for Unicode. If there are no proper options for Unicode, I would get rid of this library and find (write) a better one.
我需要这个来让古老的代码正常工作。它不是线程安全的,因为它返回一个指向内部静态数组的指针。 @red-soft-adair 答案会向相反方向转换。
I needed this for a hack to get ancient code working. It is not thread safe because it is returning a pointer to an internal static array. @red-soft-adair answer converts in the opposite direction.