Ken, Your function doesn't handle strings with null bytes in them correctly. Plus you are now dealing with a char* instead of a std::string, you will have much less headaches dealing with a std::string. You'll also be protected by RAII so it will be impossible to leak memory.
If your function is performance critical you should just dereference the Utf8Value directly in your function so no extra copy is performed. On Wed, Feb 1, 2012 at 10:21 AM, Kenneth Shaw <[email protected]> wrote: > I do this: > > // convert a v8::String to a (char*) -- any call to this should later be > free'd > static inline char *TO_CHAR(Handle<Value> val) { > String::Utf8Value utf8(val->ToString()); > > int len = utf8.length() + 1; > char *str = (char *) calloc(sizeof(char), len); > strncpy(str, *utf8, len); > > return str; > } > > Then, anywhere in your code, you can do this: > > char *x = TO_CHAR(v8_str); > printf("%s", x); > free(x); > > -Ken > > > > On Sun, Jan 29, 2012 at 6:30 PM, Ben Noordhuis <[email protected]> wrote: > > On Mon, Jan 30, 2012 at 00:22, Mark Volkmann <[email protected]> > wrote: > >> Is this the best way to get a C string from a Local<Value> that is > really a > >> Local<String>? > >> > >> if (value->IsString()) { > >> String::Utf8Value utfStr(value); > >> char* s = (char*) *utfStr; > >> } > > > > Depends on what you do with s, it becomes a dangling pointer the > > moment utfStr goes out of scope. Otherwise it's fine. > > > > -- > > Job Board: http://jobs.nodejs.org/ > > Posting guidelines: > https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines > > You received this message because you are subscribed to the Google > > Groups "nodejs" group. > > To post to this group, send email to [email protected] > > To unsubscribe from this group, send email to > > [email protected] > > For more options, visit this group at > > http://groups.google.com/group/nodejs?hl=en?hl=en > > -- > Job Board: http://jobs.nodejs.org/ > Posting guidelines: > https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines > You received this message because you are subscribed to the Google > Groups "nodejs" group. > To post to this group, send email to [email protected] > To unsubscribe from this group, send email to > [email protected] > For more options, visit this group at > http://groups.google.com/group/nodejs?hl=en?hl=en > -- Job Board: http://jobs.nodejs.org/ Posting guidelines: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines You received this message because you are subscribed to the Google Groups "nodejs" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/nodejs?hl=en?hl=en
