将WCHAR[260]转换为std::string

4
我从Windows的(PROCESSENTRY32)pe32.szExeFile获取了一个WCHAR[MAX_PATH]。以下方法均不起作用:
std::string s;
s = pe32.szExeFile; // compile error. cast (const char*) doesnt work either

并且

std::string s;
char DefChar = ' ';
WideCharToMultiByte(CP_ACP,0,pe32.szExeFile,-1, ch,260,&DefChar, NULL);
s = pe32.szExeFile;

6
你真的需要将它作为std::string吗?它应该可以直接转换为std::wstring,就像这样:std::wstring s(pe32.szExeFile); - Jerry Coffin
4个回答

3

对于你的第一个例子,你可以直接执行:

std::wstring s(pe32.szExeFile);

and for second:

char DefChar = ' ';
WideCharToMultiByte(CP_ACP,0,pe32.szExeFile,-1, ch,260,&DefChar, NULL);
std::wstring s(pe32.szExeFile);

因为 std::wstring 具有 char* 构造函数


两者都不起作用,出现相同的错误。错误:C2664:'std::basic_string<_Elem,_Traits,_Ax> :: basic_string(std::basic_string<_Elem,_Traits,_Ax> :: _Has_debug_it)':无法将参数1从“WCHAR [260]”转换为“std :: basic_string <_Elem,_Traits,_Ax>”。 - user1334943
抱歉,应该使用wstring版本,现在应该可以编译了。 - EdChum
@user1334943 它能与 std::wstring s(&pe32.szExeFile) 一起使用吗? - EdChum

2
您对WideCharToMultiByte的调用看起来是正确的,只要ch是足够大的缓冲区。然而,在此之后,您希望将缓冲区(ch)分配给字符串(或使用它构造一个字符串),而不是pe32.szExeFile

2
这里有方便的 ATL 转换类;你可能想要使用其中一些,例如:
std::string s( CW2A(pe32.szExeFile) );

请注意,从Unicode UTF-16转换为ANSI可能会有数据丢失。如果您想进行无损转换,可以将UTF-16转换为UTF-8,并在std::string中存储UTF-8。
如果您不想使用ATL,则可以使用一些便利的免费C++包装器来包装原始Win32 WideCharToMultiByte,以使用STL字符串从UTF-16转换为UTF-8

1
#ifndef __STRINGCAST_H__
#define __STRINGCAST_H__

#include <vector>
#include <string>
#include <cstring>
#include <cwchar>
#include <cassert>

template<typename Td>
Td string_cast(const wchar_t* pSource, unsigned int codePage = CP_ACP);

#endif // __STRINGCAST_H__

template<>
std::string string_cast( const wchar_t* pSource, unsigned int codePage )
{
    assert(pSource != 0);
    size_t sourceLength = std::wcslen(pSource);
    if(sourceLength > 0)
    {
        int length = ::WideCharToMultiByte(codePage, 0, pSource, sourceLength, NULL, 0, NULL, NULL);
        if(length == 0)
            return std::string();

        std::vector<char> buffer( length );
        ::WideCharToMultiByte(codePage, 0, pSource, sourceLength, &buffer[0], length, NULL, NULL);

        return std::string(buffer.begin(), buffer.end());
    }
    else
        return std::string();

}

使用以下模板:
PWSTR CurWorkDir;
std::string CurWorkLogFile;

CurWorkDir = new WCHAR[length];

CurWorkLogFile = string_cast<std::string>(CurWorkDir);

....


delete [] CurWorkDir;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接