无法将QString转换为WChar数组
Unable to convert QString to WChar Array
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*
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- 比较嵌套 for 循环中的两个 wchar 数组?
- 在 unicode 中将 WCHAR 数组转换为 std::string?
- 用相同的值填充了 wchar 数组元素
- 无法将QString转换为WChar数组
- 将WCHAR数组作为LPARAM发送到winproc的正确方法是什么?
- 通过引用传递wchar数组
- 使用矢量<wchar>而不是动态分配的 WCHAR 数组