Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to convert QString to WChar Array

Tags:

c++

qt

qt5

QString processName = "test.exe";
QString::toWCharArray(processName);

I'm getting the following error:

error: C2664: 'QString::toWCharArray' : cannot convert parameter 1 from 'QString' to 'wchar_t *'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
like image 380
user2317537 Avatar asked Nov 30 '22 01:11

user2317537


2 Answers

You're using it incorrectly. You should be calling toWCharArray on the QString you want to convert and passing it a pointer to the first element of an array you have allocated:

wchar_t array[9];
QString processName = "test.exe";
processName.toWCharArray(array);

This fills array with the contents of processName.

like image 64
Joseph Mansfield Avatar answered Dec 05 '22 17:12

Joseph Mansfield


I found the current answer is not enough, 'array' may contain unknown characters because no zero termination to 'array'.

I had this bug in my app and spent a long time to figure it out.

A better way should be looking like this:

QString processName = "test.exe";
wchar_t *array = new wchar_t[processName.length() + 1];
processName.toWCharArray(array);
array[processName.length()] = 0;

// Now 'array' is ready to use
... ...

// then delete in destructor
delete[] array;
like image 28
Jake W Avatar answered Dec 05 '22 18:12

Jake W