View Full Version : QString to Unicode to char*
Daxos
2nd November 2010, 11:16
Hi all,
I want to be able to convert my QString in unicode format and the convert it in char*.
I have try with the following code but I have a casting problem (my QByteArray contains only the first character).
QByteArray xByteArray((const char *)qsTmp.unicode(), qsTmp.size()*2);
Any Suggestions?
with regards, Dax
tbscope
2nd November 2010, 11:30
Let's see:
The QString class provides a Unicode character string
That's already taken care of.
Now, to turn it into a char pointer:
QString myString("Hello world");
char *myStringChars = myString.toUtf8().data();
Daxos
2nd November 2010, 11:51
Thankyou tbscope,
are you sure that this code work correctly? My debugger (VS2005) show me bad characters in myStringChars but I don't know if is a format-code problem.
tbscope
2nd November 2010, 12:55
You mean you actually have a unicode string?
Yes, that's correct.
Understand what a unicode string is.
ChrisW67
2nd November 2010, 21:24
Now, to turn it into a char pointer:
QString myString("Hello world");
char *myStringChars = myString.toUtf8().data();
That's likely to end in tears. QString::toUtf8() returns a temporary QByteArray, data() returns a pointer to its data buffer, and then the temporary QByteArray ceases to exist. Ultimately, you get a char* to a buffer inside a temporary object that no longer exists and can therefore be overwritten by other machine processes.
You need to control the scope of the QByteArray:
QByteArray ba = myString.toUtf8();
char *myStringChars = ba.data();
// do stuff with myStringChars
// let ba go out of scope
tbscope
3rd November 2010, 04:22
Yes, now I remember it :-)
I knew there was something wrong with it.
Daxos
3rd November 2010, 08:04
Ok, thanks :)
sysmaniac
4th November 2010, 17:56
Consider using the qPrintable macro.
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.