无法将QString转换为WChar数组

Unable to convert QString to WChar Array

本文关键字:WChar 数组 转换 QString      更新时间:2023-10-16
QString processName = "test.exe";
QString::toWCharArray(processName);

我得到以下错误:

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

你用错了。您应该在要转换的QString上调用toWCharArray,并将指向已分配数组的第一个元素的指针传递给它:

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

processName的内容填充array

我发现当前的答案是不够的,'array'可能包含未知字符,因为'array'没有零终止。

我的应用程序有这个bug,我花了很长时间来解决它。

一个更好的方式应该是这样的:

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;

1行整洁解:

processName.toStdWString().c_str()

我用了Jake W的答案。他正在使用toWCharArray方法。不幸的是,这个方法不终止字符串,这就是为什么它没有在我的情况下工作。这个效果很好:

QString processName = "test.exe";
(wchar_t*)processName.utf16();
#include "QtCore/QVector"
// ...
QVector<wchar_t> wcharVector(myQString.size() + 1);
myQString.toWCharArray(wcharVector.data());
wcharVector[myQString.size()] = 0;
// Now wcharVector.data() is wchar_t*