Hesam Qodsi
Hesam Qodsi

Reputation: 1585

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?

Upvotes: 3

Views: 5006

Answers (4)

JenyaKh
JenyaKh

Reputation: 2508

BSTR oldStr;

QString newStr{QString::fromWCharArray(oldStr)};

Upvotes: 1

convexbytes
convexbytes

Reputation: 182

BSTR strings consist on two parts: four bytes for the string length; and the content it self which can contain null characters.

The short way to do it would be:

  1. Convert QString to a two-byte null terminated string using QString::utf16. Do not use toWCharArray, a wide char is different on windows (two bytes) and linux (four bytes) (I know COM is microsoft tech, but better be sure)

  2. Use SysAllocString to create a BSTR string that contains the string length already.

  3. Optionally free the BSTR string with SysFreeString when you are done using it. Please read the following article to know when you need to release.

https://learn.microsoft.com/en-us/cpp/atl-mfc-shared/allocating-and-releasing-memory-for-a-bstr?view=vs-2017

BSTR bstr = ::SysAllocString(QString("stuff").utf16())
// use it
::SysFreeString(bstr)

To convert from BSTR to QString, you can reinterpret-cast BSTR to a ushort pointer, and then use QString::fromUtf16. Remember to free the BSTR when you are done with it.

QString qstr = QString::fromUtf16(reinterpret_cast<ushort*>(bstr));

The next useful article explains BSTR strings very well.

https://www.codeproject.com/Articles/13862/COM-in-plain-C-Part

Upvotes: 1

R&#233;my Greinhofer
R&#233;my Greinhofer

Reputation: 185

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

Upvotes: 2

j_kubik
j_kubik

Reputation: 6181

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.

Upvotes: 5

Related Questions