如何将 char* 转换为 wchar_t*?

How to convert char* to wchar_t*?(如何将 char* 转换为 wchar_t*?)
本文介绍了如何将 char* 转换为 wchar_t*?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我尝试过实现这样的功能,但不幸的是它不起作用:

I've tried implementing a function like this, but unfortunately it doesn't work:

const wchar_t *GetWC(const char *c)
{
    const size_t cSize = strlen(c)+1;
    wchar_t wc[cSize];
    mbstowcs (wc, c, cSize);

    return wc;
}

我的主要目标是能够在 Unicode 应用程序中集成普通字符字符串.非常感谢你们提供的任何建议.

My main goal here is to be able to integrate normal char strings in a Unicode application. Any advice you guys can offer is greatly appreciated.

推荐答案

使用 std::wstring 而不是 C99 变长数组.当前标准保证 std::basic_string 的连续缓冲区.例如,

Use a std::wstring instead of a C99 variable length array. The current standard guarantees a contiguous buffer for std::basic_string. E.g.,

std::wstring wc( cSize, L'#' );
mbstowcs( &wc[0], c, cSize );

C++ 不支持 C99 可变长度数组,因此如果您将代码编译为纯 C++,它甚至无法编译.

C++ does not support C99 variable length arrays, and so if you compiled your code as pure C++, it would not even compile.

随着更改,您的函数返回类型也应该是 std::wstring.

With that change your function return type should also be std::wstring.

记得在main中设置相关的locale.

Remember to set relevant locale in main.

例如,setlocale( LC_ALL, "" ).

这篇关于如何将 char* 转换为 wchar_t*?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Prevent class inheritance in C++(防止 C++ 中的类继承)
Why should I declare a virtual destructor for an abstract class in C++?(为什么要在 C++ 中为抽象类声明虚拟析构函数?)
Why is Default constructor called in virtual inheritance?(为什么在虚拟继承中调用默认构造函数?)
C++ cast to derived class(C++ 转换为派生类)
C++ virtual function return type(C++虚函数返回类型)
Is there any real risk to deriving from the C++ STL containers?(从 C++ STL 容器派生是否有任何真正的风险?)