Friday, September 30, 2016

std::string to std::wstring conversion (and vice versa) using Windows API



#pragma once

#include <windows.h>
#include <string>

inline std::wstring multi2wide(const std::string& str, UINT codePage = CP_THREAD_ACP)
{
    if (str.empty())
    {
        return std::wstring();
    }

    int required = ::MultiByteToWideChar(codePage, 0, str.data(), (int)str.size(), NULL, 0);
    if (0 == required)
    {
        return std::wstring();
    }

    std::wstring str2;
    str2.resize(required);

    int converted = ::MultiByteToWideChar(codePage, 0, str.data(), (int)str.size(), &str2[0], str2.capacity());
    if (0 == converted)
    {
        return std::wstring();
    }

    return str2;
}

inline std::string wide2multi(const std::wstring& str, UINT codePage = CP_THREAD_ACP)
{
    if (str.empty())
    {
        return std::string();
    }

    int required = ::WideCharToMultiByte(codePage, 0, str.data(), (int)str.size(), NULL, 0, NULL, NULL);
    if (0 == required)
    {
        return std::string();
    }

    std::string str2;
    str2.resize(required);

    int converted = ::WideCharToMultiByte(codePage, 0, str.data(), (int)str.size(), &str2[0], str2.capacity(), NULL, NULL);
    if (0 == converted)
    {
        return std::string();
    }

    return str2;
}

1 comment: