Jules helping Timur back in 2012… like a little gem of JUCE history here.
Just for fun,
works on OSX but fails on Android (just get
However, :), when you split it:
wtf = myJuceString.toStdString(); thisWorks = wtf.c_str();
… it works! yum.
That’s a crash waiting to happen and Android is making sense here:
toStdString is creating a new stack object of type
std::string which goes out of scope. Take a look at the method:
//in juce_String.h: /** */ std::string toStdString() const;
If you really wanted to convert a String to a const char*, you could use
This is an old topic, but I just stumbled upon this.
@jrlanglois wrote: “That’s a crash waiting to happen”, referring to
Just curious: Can someone explain, why this would result in a crash? Not quite understanding the stack object explanation from @jrlanglois.
The moral of the story is that you outta be using
String::toRawUTF8() because the ownership of the character pointer is still maintained by the source
In other words, the scope of the result from
myJuceString.toStdString().c_str() is invalid. So, basically in this case, the String object is creating a std::string that is immediately going out of scope, and you’re trying to get a char* out of it (which would be a garbage pointer at this point).
Thanks for the explanation. After I saw your comment, I switched to “toRawUTF8()”.
This is tricky!
So this would also crash?
printf("%s", myJuceString.toStdString().c_str() )
Yep, that would crash.
Maybe I’m not following the whole discussion, but what about getCharPointer()? I use this all the time to post debug printf type messages from JUCE Strings…
That is IMHO the correct solution. toRawUtf8() roundtrips through StringEncodingConverter, so it might be ephemeral as well. On most current platforms the raw string is UTF8, so it might be aequivalent.
getCharPointer() only accesses the strings memory, so it will stay valid unless the string is changed.