locale の対応状況調査(その3)

id:logion:20060208#p4 でなんともしょんぼりな結果が出た C++ の locale ですが、C の場合と同様にグローバルに設定すると正常に動くことがわかりました。
変更箇所には「ここを変更」のコメントが書いてあります。

// どこかで最初に 1 度だけ std::locale::global(std::locale("")); を実行しておく
void convertMultiByteToWideChar(const char* pStrMultiByte, std::wstring& rStrWideChar)
{
  std::string strMultiByte(pStrMultiByte);
  std::locale localeCurrent; // ここを変更

  std::mbstate_t stateWChar = 0;
  const std::codecvt& rConvertMultiByteToWChar =
    std::use_facet >(localeCurrent);
  const char* pNextMultiByteChar = NULL;
  int sizeStrWChar = strMultiByte.size() * 2;
  wchar_t* pStrWChar = new wchar_t[sizeStrWChar + 1];
  wchar_t* pNextWChar = NULL;
  int result = rConvertMultiByteToWChar.in(stateWChar, strMultiByte.data(),
          strMultiByte.data() + strMultiByte.size(), pNextMultiByteChar,
          pStrWChar, pStrWChar + sizeStrWChar, pNextWChar);
  *pNextWChar = L'\0';

  rStrWideChar = pStrWChar;
  delete pStrWChar;
}

void convertWideCharToMultiByte(const wchar_t* pStrWideChar, std::string& rStrMultiByte)
{
  std::wstring strWideChar(pStrWideChar);
  std::locale localeCurrent; // ここを変更

  std::mbstate_t stateMultiByte = 0;
  const std::codecvt& rConvertWCharToMultiByte =
    std::use_facet >(localeCurrent);
  const wchar_t* pNextWChar = NULL;
  int sizeStrMultiByte = strWideChar.size() * 3;
  char* pStrMultiByte = new char[sizeStrMultiByte + 1];
  char* pNextMultiByteChar = NULL;
  int result = rConvertWCharToMultiByte.out(stateMultiByte, strWideChar.data(),
          strWideChar.data() + strWideChar.size(), pNextWChar,
          pStrMultiByte, pStrMultiByte + sizeStrMultiByte, pNextMultiByteChar);
  *pNextMultiByteChar = '\0';

  rStrMultiByte = pStrMultiByte;
  delete pStrMultiByte;
}