C++ 将 const char* 转换为 wstring

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10737644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:24:02  来源:igfitidea点击:

Convert const char* to wstring

c++

提问by Johannes Klau?

I'm working on a native extension for a zinc based flash application and I need to convert a const char*to a wstring.

我正在为基于锌的 Flash 应用程序开发本机扩展,我需要将 a 转换const char*wstring.

This is my code:

这是我的代码:

mdmVariant_t* appendHexDataToFile(const zinc4CallInfo_t *pCallInfo, int paramCount, mdmVariant_t **params) {

    if(paramCount >= 2) {
        const char *file    = mdmVariantGetString(params[0]);
        const char *data    = mdmVariantGetString(params[1]);

        return mdmVariantNewInt(native.AppendHexDataToFile(file, data));
    }
    else {
        return mdmVariantNewBoolean(FALSE);
    }
}

But native.AppendHexDataToFile()needs two wstring. I'm not very good with C++ and I think all those different string types are totally confusing and I didn't find something useful in the net. So I'm asking you guys how to do it.

native.AppendHexDataToFile()需要两个wstring。我对 C++ 不是很好,我认为所有这些不同的字符串类型都令人困惑,而且我没有在网上找到有用的东西。所以想请教大家怎么办。

Edit: The Strings are UTF-8 and I'm using OSX and Windows XP/Vista/7

编辑:字符串是 UTF-8,我使用的是 OSX 和 Windows XP/Vista/7

采纳答案by LihO

I recommend you using std::stringinstead of C-style strings (char*) wherever possible. You can create std::stringobject from const char*by simple passing it to its constructor.

我建议您尽可能使用std::stringC 风格的字符串 ( char*)而不是。您可以通过简单地将std::string对象const char*传递给其构造函数来创建对象。

Once you have std::string, you can create simple function that will convert std::stringcontaining multi-byte UTF-8 characters to std::wstringcontaining UTF-16 encoded points (16bit representation of special characters from std::string).

一旦有了std::string,您就可以创建简单的函数,将std::string包含多字节 UTF-8 字符转换为std::wstring包含 UTF-16 编码点(来自 的特殊字符的 16 位表示std::string)。

There are more ways how to do that, here's the way by using MultiByteToWideChar function:

有更多方法可以做到这一点,这里是使用MultiByteToWideChar 函数的方法

std::wstring s2ws(const std::string& str)
{
    int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
    std::wstring wstrTo( size_needed, 0 );
    MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
    return wstrTo;
}

Check these questions too:
Mapping multibyte characters to their unicode point representation
Why use MultiByteToWideCharArray to convert std::string to std::wstring?

也请检查这些问题:将
多字节字符映射到它们的 unicode 点表示
为什么使用 MultiByteToWideCharArray 将 std::string 转换为 std::wstring?

回答by anhoppe

AFAIK this works only from C++11 and above:

AFAIK 这仅适用于 C++11 及更高版本:

#include <codecvt>

// ...

std::wstring stringToWstring(const std::string& t_str)
{
    //setup converter
    typedef std::codecvt_utf8<wchar_t> convert_type;
    std::wstring_convert<convert_type, wchar_t> converter;

    //use converter (.to_bytes: wstr->str, .from_bytes: str->wstr)
    return converter.from_bytes(t_str);
}

Reference answer

参考答案

回答by SaeidMo7

You can convert charstring to wstringdirectly as following code:

您可以将char字符串wstring直接转换为以下代码:

char buf1[] = "12345678901234567890";
wstring ws(&buf1[0], &buf1[20]);

回答by Edward Loper

You need a library that can encode/decode UTF8. Unfortunately, this functionality isn't included with the std c++ library. Here's one library you might use: http://utfcpp.sourceforge.net/

您需要一个可以编码/解码 UTF8 的库。不幸的是,此功能未包含在 std c++ 库中。这是您可能会使用的一个库:http: //utfcpp.sourceforge.net/

Here's an example use of it:

这是它的一个使用示例:

utf8::utf8to32(bytes.begin(), bytes.end(), std::back_inserter(wstr));

回答by Violet Giraffe

An addition to the answerfrom @anhoppe. Here's how to convert char*:

对@anhoppe的回答的补充。转换方法char*如下:

#include <codecvt>
#include <locale> 

// ...

std::wstring stringToWstring(const char* utf8Bytes)
{
    //setup converter
    using convert_type = std::codecvt_utf8<typename std::wstring::value_type>;
    std::wstring_convert<convert_type, typename std::wstring::value_type> converter;

    //use converter (.to_bytes: wstr->str, .from_bytes: str->wstr)
    return converter.from_bytes(utf8Bytes);
}

And here's how to convert char*if you also already know the length of the buffer:

char*如果您也已经知道缓冲区的长度,这里是如何转换:

#include <codecvt>

// ...

std::wstring stringToWstring(const char* utf8Bytes, const size_t numBytes)
{
    //setup converter
    using convert_type = std::codecvt_utf8<typename std::wstring::value_type>;
    std::wstring_convert<convert_type, typename std::wstring::value_type> converter;

    //use converter (.to_bytes: wstr->str, .from_bytes: str->wstr)
    return converter.from_bytes(utf8Bytes, utf8Bytes + numBytes);
}

回答by bames53

On OS X wstring uses UTF-32 rather than UTF-16. You can do the conversion like this:

在 OS X 上 wstring 使用 UTF-32 而不是 UTF-16。您可以像这样进行转换:

#include <codecvt>
#include <string>

// make facets usable by giving them a public destructor
template <class Facet>
class usable_facet
    : public Facet
{
public:
    template <class ...Args>
        usable_facet(Args&& ...args)
            : Facet(std::forward<Args>(args)...) {}
    ~usable_facet() {}
};

std::wstring s2ws(std::string const &s) {
    std::wstring_convert<
        usable_facet<std::codecvt<char32_t,char,std::mbstate_t>>
        ,char32_t> convert;
    std::u32string utf32 = convert.from_bytes(s);
    static_assert(sizeof(wchar_t)==sizeof(char32_t),"char32_t and wchar_t must have same size");
    return {begin(utf32),end(utf32)};
}

回答by Samy Arous

Here's a code I found;

这是我找到的代码;

std::wstring StringToWString(const std::string& s)
 {
 std::wstring temp(s.length(),L' ');
 std::copy(s.begin(), s.end(), temp.begin());
 return temp; 
 }

And here's the original forum post with a possible second solution using the windows API function MultiByteToWideChar:

这是使用 Windows API 函数 MultiByteToWideChar 的可能的第二个解决方案的原始论坛帖子:

http://forums.codeguru.com/archive/index.php/t-193852.html

http://forums.codeguru.com/archive/index.php/t-193852.html