PDA

View Full Version : Convertion from QString to unsigned char *



vcp
13th August 2010, 16:40
Hi,

Sorry to bring this issue to light again, but I need to fix this.

I'm with a problem to convert one type QString to unsigned char *.
I've been reading various documents about this issue and making tests for days, but can not solve the problem.

Here's the situation:



QString str = "NONONONONO";
unsigned char * ucTest;
ucTest = (unsigned char *) str.toLatin1().data();


The result of the conversion seems to work correctly.
But when I pass the variable to the process ucTest result is not correct!

Now, if I define directly and pass it through the same process, so now it works.



unsigned char * ucText = "NONONONONO";


now I pass the variable to the process the result is correct!

Why does this happen?
Please any of you could try to help me solve this?

Thank a lot.

tbscope
13th August 2010, 17:48
ucTest = (unsigned char *) str.toLatin1().data();

Nope, that is not correct.

QString::data() doesn't return what you think it returns.
Use this instead:


ucTest = (unsigned char *) str.toAscii().data();

vcp
13th August 2010, 19:05
Then, what exactly QString::data() returns?

tnx

squidge
13th August 2010, 19:15
str.toAscii().data() is the same as str.toLatin1().data unless you use setCodecForCStrings().

Note that there is a temporary object being created here, so the return value isn't valid when the statement is complete. So:


ucTest = (unsigned char *) str.toLatin1().data();


Will never work correctly, but this will:


myFunc((unsigned char *) str.toLatin1().data());

myFunc will be passed a pointer which will not be deleted until after myFunc returns.

If you want to pointer to remain valid, create a QByteArray:


QByteArray ascii = str.toLatin1();
ucTest = (unsigned char *) ascii.data();

tbscope
13th August 2010, 19:24
str.toAscii().data() is the same as str.toLatin1().data unless you use setCodecForCStrings().

Indeed. Hmm, I did look at the QString documentation and I can swear that the I read the toLatin1() returned a QString. Strange. Sorry about the confusion.

vcp
13th August 2010, 19:26
Dear fatjuicymole,

His explanation and example were really helpful!
Now I understand perfectly that issue, and certainly
was extremely helpful to me.

Thank you very much

I hope at some point could also help with my
knowledge in this way.

Thanks again.