Conversion from WTF::String to const char *

1,766 views
Skip to first unread message

pratik dand

unread,
Mar 11, 2015, 5:49:55 AM3/11/15
to chromi...@chromium.org
Dear,

What is the safest way to convert a 'WTF::String' to 'const char *' and 'v8::String::Utf8Value' to 'WTF::String'?

I need to convert a Javascript source code which is a WTF::String to a const char * which is to be passed to the v8::String::NewFromUtf8.
The result after evaluating the script is a v8::String::Utf8Value which needs to be converted back to WTF::String.

For performing a conversion from 'WTF::String' to 'const char *',  I am using the .latin().data() and .ascii.data() functions.
Any help/hint towards some functions will be helpful.

Christian Biesinger

unread,
Mar 11, 2015, 6:07:40 PM3/11/15
to pratik...@gmail.com, chromium-dev

For the former: use .utf8().data().

-christian

--
--
Chromium Developers mailing list: chromi...@chromium.org
View archives, change email options, or unsubscribe:
http://groups.google.com/a/chromium.org/group/chromium-dev

Elliott Sprehn

unread,
Mar 11, 2015, 6:14:29 PM3/11/15
to Christian Biesinger, pratik...@gmail.com, chromium-dev
On Wed, Mar 11, 2015 at 3:06 PM, Christian Biesinger <cbies...@chromium.org> wrote:

For the former: use .utf8().data().

Note that the return value of utf8() is a malloced buffer, so the data() pointer will be free'd right after that expression. You need to save the CString from utf8() somewhere (like the stack) if you plan to pass the data() around outside a single expression.

pratik dand

unread,
Mar 12, 2015, 10:46:39 PM3/12/15
to Elliott Sprehn, Christian Biesinger, chromium-dev
Thanks for helping with converting from WTF::String to const char *.
For the latter i.e. converting from v8::String::Utf8Value to WTF::String, I converted the v8::String::Utf8Value to a std:: string and then converting the std::string to WTF::String is trivial using s_ctr(). This worked for me but is it safe?

--
Pratik

Christian Biesinger

unread,
Mar 13, 2015, 12:06:46 AM3/13/15
to pratik dand, Elliott Sprehn, chromium-dev
That constructor interprets the data as latin1 (ISO-8859-1), not as UTF-8. So it is incorrect for non-ASCII characters.

Perhaps:

  WTF::String str = WTF::UTF8Encoding().decode(your_std_string.c_str(), your_std_string.size());

-christian

Elliott Sprehn

unread,
Mar 13, 2015, 12:47:11 AM3/13/15
to Christian Biesinger, pratik dand, chromium-dev
The bindings do:

V8StringResource<TreatNullAndUndefinedAsNullString> cppValue = v8StringValue;
if (!cppValue.prepare())
    return;
String string = cppValue;

Object#toString() can throw a exception in JS, so you check prepare() to see if the conversion to a string succeeded.

Reply all
Reply to author
Forward
0 new messages