nprogram’s blog

気ままに、プログラミングのトピックについて書いていきます

マルチバイト文字列(std::string)とワイド文字列(std::wstring)の間の変換を行うライブラリが便利すぎる [C++]

最近、仕事でMFCのアプリケーションをUnicode対応する仕事をしていて、以下のライブラリを使わせていただきました。 マルチバイト文字列(std::string)とワイド文字列(std::wstring)の間の変換を行うライブラリが便利すぎたので、紹介させてください。

本ライブラリを使用すれば、非常に簡単にマルチバイト文字列(std::string)とワイド文字列(std::wstring)の間の変換が可能です。

qiita.com

static inline std::wstring cp_to_wide(const std::string &s, UINT codepage)
{
  int in_length = (int)s.length();
  int out_length = MultiByteToWideChar(codepage, 0, s.c_str(), in_length, 0, 0); 
  std::wstring result(out_length, L'\0');
  if (out_length) MultiByteToWideChar(codepage, 0, s.c_str(), in_length, &result[0], out_length);
  return result;
}
static inline std::string wide_to_cp(const std::wstring &s, UINT codepage)
{
  int in_length = (int)s.length();
  int out_length = WideCharToMultiByte(codepage, 0, s.c_str(), in_length, 0, 0, 0, 0); 
  std::string result(out_length, '\0');
  if (out_length) WideCharToMultiByte(codepage, 0, s.c_str(), in_length, &result[0], out_length, 0, 0); 
  return result;
}