Skip to content

Instantly share code, notes, and snippets.

@vurdalakov
Created September 30, 2016 02:26
Show Gist options
  • Save vurdalakov/29d05d1820a241e3ba482ceaf28af2de to your computer and use it in GitHub Desktop.
Save vurdalakov/29d05d1820a241e3ba482ceaf28af2de to your computer and use it in GitHub Desktop.
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment