How can i split a wchar_t / TCHAR / WCHAR / LPTSTR into a QStringList?

440 Views Asked by At

While working with the Win32API, the function i must use returns its results by writing them to buffer of type LPTSTR as well as the individual number of characters that were written.enter code here

As this buffer is a string, and the function can return multiple values, the actual result data look something like this:

Value1\0Value2\0Value3\0\0

What is the best way to get this into a QStringList?

1

There are 1 best solutions below

7
On

LPTSTR = Long Pointer to TCHAR. On modern systems (those with unicode support) this is synonymous with a WCHAR array.

Since your output buffer will contain characters where each is two bytes it is thus compatible with UTF16.

QString has a fromUtf16 static method which requires a simple cast to satisfy the compiler.

In this case, we MUST also specify the total length of the entire string. Failure to do this results in QString only reading the input data up until the first null character, ignoring any other result data.

Once we actually have a QString to work with, splitting it is simple. Call QString's split() method specifying a null character wrapped in a QChar.

Optionally, and required in my case, specifying SplitBehavior as SkipEmptyParts ensures that no empty strings (the result of parsing the null character) end up in my desired result (the QStringList of values).

Example:

// The data returned by the API call.
WCHAR *rawResultData = L"Value1\0Value2\0Value3\0";

// The number of individual characters returned.
quint64 numberOfWrittenCharacters = 22;

// Create a QString from the returned data specifying
// the size.
QString rString = 
QString::fromUtf16((const ushort *)rawResultData, numberOfWrittenCharacters);

// Finally, split the string into a QStringList
// ignoring empty results.
QStringList results = 
rString.split(QChar(L'\0'), QString::SkipEmptyParts);