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

Convert WCHAR[260] to std::string

本文关键字:std 转换 string WCHAR      更新时间:2023-10-16

我从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;

对于您的第一个示例,您可以执行以下操作:

std::wstring s(pe32.szExeFile);

第二:

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

由于std::wstring有一个char* CTOR

你对WideCharToMultiByte的调用看起来是正确的,前提是ch是一个足够大的缓冲区。 但是,在之后,您希望分配缓冲区(ch)到字符串(或使用它来构造字符串),而不是 pe32.szExeFile .

ATL有方便的转换类;你可能想使用其中的一些,例如:

std::string s( CW2A(pe32.szExeFile) );

但请注意,从 Unicode UTF-16 到 ANSI 的转换可能是有损的。如果您不想进行非有损转换,则可以从 UTF-16 转换为 UTF-8,并将 UTF-8 存储在 std::string 中。

如果您不想使用 ATL,可以使用原始 Win32 WideCharToMultiByte 周围有一些方便的免费C++包装器,可以使用 STL 字符串从 UTF-16 转换为 UTF-8。

#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;