Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast vs ToXXX for value handles in v8

Tags:

c++

javascript

v8

I'm embedding V8 as an auxiliary language in a C++ program.

I retrieve a Handle<Value> from V8 when I call something like

Handle<Value> value_handle = context->Global()->Get(key_handle);

I can then find out that it is (say) a string with value_handle->IsString(). And if so I can convert it to a Handle<String> to access its string-specific methods.

But there seems to be two ways of doing that, either:

Handle<String> string = value_handle->ToString();

or

Handle<String> string = Handle<String>::Cast(value_handle);

However, for Arrays and Functions, there is no toArray() or toFunction methods, just the casting.

So my question is: a) are the ToXXX just syntactic sugar for casting? and, if not b) what is the ToXXX method doing?

like image 260
Ian Avatar asked Feb 22 '13 04:02

Ian


1 Answers

ToXXX functions perform type coercions as described in subsections of section 9 of ECMA-262 5th. For example ToString is described in section 9.8: when given a non-string value it'll return an appropriate string representation of it, if you are passing object it'll call toString method on it (or valueOf if toString is not present). Relevant code for ToString: in api.cc Value::ToString that calls into runtime.js ToString

On the other hand Handle<XXX>::Cast(...) does no coercions. It's just a type cast for handles. Essentially it is just a static_cast<XXX*>. In debug mode Handle<T>::Cast(...) is checked and aborts execution when types do not match. It would be a fatal error if you are given a Handle<Value> containing an Object and you are trying to cast it to a Handle<String>. In release mode casting to an incompatible type will just later lead to weird results and possibly crashes, when you try to use the result of the cast. Relevant code in v8.h Handle<T>::Cast which delegates to (for example) String::Cast which checks the cast (if checks are enabled) via String::CheckCast.

like image 86
Vyacheslav Egorov Avatar answered Oct 17 '22 11:10

Vyacheslav Egorov