Juce::String to const char*?

Jules helping Timur back in 2012… like a little gem of JUCE history here. :slight_smile:

5 Likes

Just for fun,

myJuceString.toStdString().c_str();

works on OSX but fails on Android (just get 0x00 repeated).

However, :), when you split it:

wtf = myJuceString.toStdString();
thisWorks = wtf.c_str();

… it works! yum.

1 Like

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;

No kidding!


If you really wanted to convert a String to a const char*, you could use String::toRawUTF8().

3 Likes

Okay, I’ll take this one… hahaha… @p-i only posted it!

Great thanks as always @jrlanglois!!!

This is an old topic, but I just stumbled upon this.

@jrlanglois wrote: “That’s a crash waiting to happen”, referring to myJuceString.toStdString().c_str();

Just curious: Can someone explain, why this would result in a crash? Not quite understanding the stack object explanation from @jrlanglois. :slight_smile:

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 String.

In other words, the scope of the result from c_str() in 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…

1 Like

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.
But getCharPointer() only accesses the strings memory, so it will stay valid unless the string is changed.

1 Like