Reinterpret casting a v8::Persistent<v8::Context> to a v8::Local<v8::Context>

31 views
Skip to first unread message

Elling B

unread,
Oct 13, 2020, 9:37:00 AM10/13/20
to v8-users
I found this helper method in a tutorial a couple of days ago.

It reinterpret casts a v8::Persistent to a v8::Local, with the intended use of calling V8 API functions that require a local handle to a context, without actually having to create a new v8::Local each time:

template <class TypeName>
inline v8::Local<TypeName> ToLocal(const v8::Persistent<TypeName>& persistent)
{
  return *reinterpret_cast<v8::Local<TypeName>*>(const_cast<v8::Persistent<TypeName>*>(&persistent));
}


I'm new to V8, so I find myself wondering if it's safe or not. Or if it can be safe in some cases.

Ben Noordhuis

unread,
Oct 13, 2020, 2:29:51 PM10/13/20
to v8-users
Full disclosure: that StrongPersistentToLocal() helper from the
article is my code. I introduced that trick in the Node.js code base
years ago and looks like people copied it. Mea culpa. :broken_smile:

So, it works, but it's not particularly safe. Caveats:

- don't use it on weakly persistent handles, only strong ones, and

- don't call .Reset() while the Local is still in use

Node.js (ab)uses it for performance reasons but most of the time you
should just use `Local<Value>::New(isolate, persistent)`.

Elling B

unread,
Oct 13, 2020, 3:09:56 PM10/13/20
to v8-users
Ok. Always good hearing it from the horse's mouth directly. Thanks a lot! :)
Reply all
Reply to author
Forward
0 new messages