Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

_bstr_t to UTF-8 possible?

I have a _bstr_t string which contains Japanese text. I want to convert this string to a UTF-8 string which is defined as a char *.

Can I convert the _bstr_t string to char * (UTF-8) string without losing the Japanese characters?

like image 691
Manav Sharma Avatar asked Mar 09 '09 12:03

Manav Sharma


2 Answers

Use WideCharToMultiByte() – pass CP_UTF8 as the first parameter.

Beware that BSTR can be a null pointer and that corresponds to an empty string – treat this as a special case.

like image 157
sharptooth Avatar answered Oct 27 '22 08:10

sharptooth


Here is some code that should do the conversion.

void PrintUtf8(const TCHAR* value) { 
    if (value == nullptr) {
        printf("");
        return;
    }
    int n = WideCharToMultiByte(CP_UTF8, 0, value, -1, nullptr, 0, nullptr, nullptr);
    if (n <= 0) {
        printf("");
        return;
    }
    char* buffer = new char[n];
    WideCharToMultiByte(CP_UTF8, 0, value, -1, buffer, n, nullptr, nullptr);
    printf("%s", buffer);
    delete(buffer);
}
like image 28
cdiggins Avatar answered Oct 27 '22 09:10

cdiggins