我如何使用MultiByteToWideChar?

Suh*_*pta 20 c++ winapi character-encoding visual-c++

我想将法线转换stringwstring.为此,我正在尝试使用Windows API函数MultiByteToWideChar.但它对我不起作用.

这是我做的:

string x = "This is c++ not java";
wstring Wstring;
MultiByteToWideChar( CP_UTF8 , 0 , x.c_str() , x.size() , &Wstring , 0 ); 
Run Code Online (Sandbox Code Playgroud)

最后一行产生编译器错误:

'MultiByteToWideChar' : cannot convert parameter 5 from 'std::wstring *' to 'LPWSTR'
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个错误?

此外,论证的价值应该是什么cchWideChar?好吗?

era*_*ran 37

你必须打MultiByteToWideChar两次电话:

  1. 第一次调用MultiByteToWideChar用于查找宽字符串所需的缓冲区大小.看看微软的文档 ; 它指出:

    如果函数成功并且cchWideChar为0,则返回值是lpWideCharStr指示的缓冲区所需的大小(以字符为单位).

    因此,为了MultiByteToWideChar给你所需的大小,传递0作为最后一个参数的值,cchWideChar.你也应该NULL像它前面那样传递,lpWideCharStr.

  2. 使用上一步中的缓冲区大小获取足够大的非const缓冲区以容纳宽字符串.将此缓冲区传递给另一个调用MultiByteToWideChar.而这一次,最后一个参数应该是缓冲区的实际大小,而不是0.

一个粗略的例子:

int wchars_num = MultiByteToWideChar( CP_UTF8 , 0 , x.c_str() , -1, NULL , 0 );
wchar_t* wstr = new wchar_t[wchars_num];
MultiByteToWideChar( CP_UTF8 , 0 , x.c_str() , -1, wstr , wchars_num );
// do whatever with wstr
delete[] wstr;
Run Code Online (Sandbox Code Playgroud)

另外,请注意使用-1作为cbMultiByte参数.这将使得结果字符串以null结尾,从而使您无需处理它们.

  • +1用于强调需要两次调用MultiByteToWideChar,这对于字符集转换功能至关重要. (4认同)

sta*_*x76 15

一些常见的转换:

#define WIN32_LEAN_AND_MEAN

#include <Windows.h>

#include <string>

std::string ConvertWideToANSI(const std::wstring& wstr)
{
    int count = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.length(), NULL, 0, NULL, NULL);
    std::string str(count, 0);
    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, &str[0], count, NULL, NULL);
    return str;
}

std::wstring ConvertAnsiToWide(const std::string& str)
{
    int count = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.length(), NULL, 0);
    std::wstring wstr(count, 0);
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.length(), &wstr[0], count);
    return wstr;
}

std::string ConvertWideToUtf8(const std::wstring& wstr)
{
    int count = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), wstr.length(), NULL, 0, NULL, NULL);
    std::string str(count, 0);
    WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, &str[0], count, NULL, NULL);
    return str;
}

std::wstring ConvertUtf8ToWide(const std::string& str)
{
    int count = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), NULL, 0);
    std::wstring wstr(count, 0);
    MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), &wstr[0], count);
    return wstr;
}
Run Code Online (Sandbox Code Playgroud)