Convert WCHAR [260] to std :: string

I got WCHAR [MAX_PATH] from (PROCESSENTRY32) pe32.szExeFile on Windows. The following do not work:

std::string s;
s = pe32.szExeFile; // compile error. cast (const char*) doesnt work either

and

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

Your call WideCharToMultiBytelooks correct if there chis a sufficiently large buffer. After that, however, you want to assign buffer ( ch) to a string (or use it to build a string), not pe32.szExeFile.

+1
source

In the first example, you can simply do:

std::wstring s(pe32.szExeFile);

and for the second:

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

how std::wstringhas a char*ctor

+3
source

ATL; , :

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

, , Unicode UTF-16 ANSI . , UTF-16 UTF-8 UTF-8 std::string.

If you do not want to use ATL, there are some convenient freely available C ++ shells around raw Win32 WideCharToMultiBytebefore converting from UTF-16 to UTF -8 using STL strings .

+2
source
#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();

}

and use this template as it should

PWSTR CurWorkDir;
std::string CurWorkLogFile;

CurWorkDir = new WCHAR[length];

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

....


delete [] CurWorkDir;
+1
source

All Articles