Created
November 15, 2017 07:07
-
-
Save Tocchann/345a2d1f428367749f588a1088765c8a to your computer and use it in GitHub Desktop.
std::string/wstring を使って、UNICODE と UTF-8 を相互変換(抜粋コード)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
std::string ToUtf8Str( const wchar_t* value ) | |
{ | |
_ASSERTE( value != nullptr ); | |
if( value == nullptr || *value == L'\0' ){ | |
return ""; | |
} | |
int needLength = WideCharToMultiByte( CP_UTF8, 0, value, -1, nullptr, 0, nullptr, nullptr ); | |
if( needLength < 1 ){ | |
return ""; | |
} | |
std::string result; | |
result.resize( needLength-1 ); // \0を含むバイト数が返ってくる | |
WideCharToMultiByte( CP_UTF8, 0, value, -1, &result[0], needLength, nullptr, nullptr ); | |
return result; | |
} | |
std::wstring ToUnicodeStr( const char* value ) | |
{ | |
_ASSERTE( value != nullptr ); | |
if( value == nullptr || *value == '\0' ){ | |
return L""; | |
} | |
int needLength = MultiByteToWideChar( CP_UTF8, 0, value, -1, nullptr, 0 ); | |
std::wstring result; | |
result.resize( needLength-1 ); | |
MultiByteToWideChar( CP_UTF8, 0, value, -1, &result[0], needLength ); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment