Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of UTF-8 char * to CString

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

like image 208
Greenhorn Avatar asked Jan 21 '23 00:01

Greenhorn


1 Answers

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).

like image 190
Serge Dundich Avatar answered Jan 28 '23 08:01

Serge Dundich