1

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());
  1. Produces

    îþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþç'Û)ÆS2¹ú¨ºú

  2. Produces

    îþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþFþš

  3. Produces

    îþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþFþš

How do I convert it?

Community
  • 1
  • 1
Petr
  • 13,747
  • 20
  • 89
  • 144

1 Answers1

2

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.

Petr
  • 13,747
  • 20
  • 89
  • 144
  • This isn't really correct usage of the _T() macro. I'd recommend you take that out since it could cause compilation to break if you enabled Microsoft Unicode. More info: https://msdn.microsoft.com/en-us/library/dybsewaf.aspx – MrEricSir Jan 22 '15 at 19:12