如何将Qt5中的QString转换为Visual Studio 2013中的LPCSTR [英] How to convert QString in Qt5 to LPCSTR in Visual Studio 2013
问题描述
我发现了这个问题(对我而言毫无用处):如何转换QString到LPCSTR(Unicode),其中大多数人可能会认为它们是重复的,但我认为它要么与不同的Qt / VS / C ++版本相关,要么没有正确答案(尽管有些标记为)。
我在Windows 7的Visual Studio 2013中使用Qt5编写了此代码,使用C ++ 11标准,它在链接的答案中使用了所有建议的解决方案:
QString test = hello world;
// 1
LPCSTR lp1 = _T(test.toLocal8Bit()。constData());
// 2
LPCSTR lp2 = _T(test.toUtf8()。toStdString()。c_str());
// 3
LPCSTR lp3 = _T(test.toLatin1()。toStdString()。c_str());
-
产品
îþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþç'Û)ÆS2¹ú¨ºú
-
可生产
îþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþFþš
-
产生
þþþþþþþþþþþþþp p b
$ b如何转换?
解决方案感谢HuntsMan @ irc.freenode.net我找到正确的解决方案:
QString test = hello world;
QByteArray test_ar = test.toLocal8Bit();
LPCSTR lp2 = _T(test_ar.constData());
问题是我退出该行代码后,就从堆栈中删除了QByteArray的副本,所以当LPCSTR指向的时候我传递的指针指向已删除的内存。
I found this (useless in my case) question: How to convert QString to LPCSTR (Unicode) which most of you probably would consider duplicate, but I think it's either related to different Qt / VS / C++ version or just has no correct answers (despite some is marked so).
I have this code using Qt5 in Visual Studio 2013 on Windows 7, using C++11 standards, it uses all of the proposed solutions in linked answer:
QString test = "hello world"; // 1 LPCSTR lp1 = _T(test.toLocal8Bit().constData()); // 2 LPCSTR lp2 = _T(test.toUtf8().toStdString().c_str()); // 3 LPCSTR lp3 = _T(test.toLatin1().toStdString().c_str());
Produces
îþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþç'Û)ÆS2¹ú¨ºú
Produces
îþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþFþš
Produces
îþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþFþš
How do I convert it?
解决方案Thanks to HuntsMan @irc.freenode.net I found the correct solution:
QString test = "hello world"; QByteArray test_ar = test.toLocal8Bit(); LPCSTR lp2 = _T(test_ar.constData());
Problem was that a copy of QByteArray got deleted from stack as soon as I exit that line of code, so pointer I passed as LPCSTR was pointing to deleted memory.
这篇关于如何将Qt5中的QString转换为Visual Studio 2013中的LPCSTR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!