Conversion of UTF-8 char * to CString

2019-03-31 06:17发布

How do I convert a string in UTF-8 char* to CString?

3条回答
走好不送
2楼-- · 2019-03-31 06:33
bool Utf8ToCString( CString& cstr, const char* utf8Str )
{
    size_t utf8StrLen = strlen(utf8Str);

    if( utf8StrLen == 0 )
    {
        cstr.Empty();
        return true;
    }

    LPTSTR* ptr = cstr.GetBuffer(utf8StrLen+1);

#ifdef UNICODE
    // CString is UNICODE string so we decode
    int newLen = MultiByteToWideChar(
                     CP_UTF8,  0,
                     utf8Str, utf8StrLen,  ptr, utf8StrLen+1
                     );
    if( !newLen )
    {
        cstr.ReleaseBuffer(0);
        return false;
    }
#else
    WCHAR* buf = (WCHAR*)malloc(utf8StrLen);

    if( buf == NULL )
    {
        cstr.ReleaseBuffer(0);
        return false;
    }

    int newLen = MultiByteToWideChar(
                     CP_UTF8,  0,
                     utf8Str, utf8StrLen,  buf, utf8StrLen
                     );
    if( !newLen )
    {
        free(buf);
        cstr.ReleaseBuffer(0);
        return false;
    }

    assert( newLen < utf8StrLen );
    newLen = WideCharToMultiByte(
                     CP_ACP,  0,
                     buf, newLen,  ptr, utf8StrLen
                     );
    if( !newLen )
    {
        free(buf);
        cstr.ReleaseBuffer(0);
        return false;
    }

    free(buf);
#endif

    cstr.ReleaseBuffer(newLen);
    return true;
}

Though this function is valid for both UNICODE and non-UNICODE configurations IMHO using UNICODE configuration in Win32 programs is much more productive (in general and in this function).

查看更多
虎瘦雄心在
3楼-- · 2019-03-31 06:46

If your string contains only ASCII-characters with codes 0 to 127 you may threat your UTF-8 string as ASCII string and initialise CString with it:

CString my_cstr((char*)my_string);

Otherwise (if your UTF-8 string contains some other characters) you have no easy way to get char* string from it.

查看更多
够拽才男人
4楼-- · 2019-03-31 06:49

Call MultiByteToWideChar with a code page of CP_UTF8, then use CString as normal.

查看更多
登录 后发表回答