Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conver QString to BSTR and vice versa

I want to convert QString to BSTR and vice versa.

This is what i try to convert QString to BSTR :

std::wstring str_ = QString("some texts").toStdWString();
BSTR bstr_ = str_.c_str();

and to convert BSTR to QString :

BSTR bstr_;
wchar_t *str_ = bstr_;
QString qstring_ = QString::fromWCharArray(str_);

Is this correct? In other words is there any data lose? If yes, what is the correct solution?

like image 385
Hesam Qodsi Avatar asked Jan 29 '26 07:01

Hesam Qodsi


2 Answers

You should probably use SysAllocString to do this - BSTR also contains length prefix, which is not included with your code.

std::wstring str_ = QString("some texts").toStdWString();
BSTR bstr_ = SysAllocString(str_.c_str());

Other than that there isn't anything to be lost here - Both BSTR and QString use 16-bit Unicode encoding, so converting between each other should not modify internal data buffers at all.

like image 132
j_kubik Avatar answered Jan 30 '26 22:01

j_kubik


To convert a BSTR to a QString you can simply use the QString::fromUtf16 function:

BSTR bstrTest = SysAllocString(L"ConvertMe");
QString qstringTest = QString::fromUtf16(bstrTest);
like image 33
Rémy Greinhofer Avatar answered Jan 30 '26 20:01

Rémy Greinhofer