Re: [nodejs] Correct use of HandleScope in an asynchronous node addon

47 views
Skip to first unread message

Ben Noordhuis

unread,
May 23, 2013, 9:41:47 AM5/23/13
to nod...@googlegroups.com
On Thu, May 23, 2013 at 4:44 AM, Cecil Rock <cecil...@gmail.com> wrote:
> I'm writing a asynchronous Node Addon, but I have been struggling to figure
> out if I need to use a HandleScope in the "After" function that calls the
> client JavaScript callback. I've seen examples showing with and without new
> scopes, but never any explanation why. Here is an example:
>
> void asyncWorkAfter(uv_work_t* req) {
> HandleScope scope; // <-- Do you need a new scope?

Yes. Rule of thumb: any function that manipulates V8 values somehow,
needs a HandleScope.

> const int argc = 1;
> Local<Value> foo = String::New("foo");
> Local<Value> argv[] = { foo };
>
> // assume I got my callback function out of req
> callback->Call(Context::GetCurrent()->Global(), argc, argv);
>
> callback.Dispose();
>
> // if i use a new HandleScope, what happens to argv when we go out of
> scope?
> // Do i need to do something like a scope.Close() to copy argv to the
> parent scope?

No, V8 takes care of that.

A Local<> is a reference to a JS value that is rooted in the current
HandleScope. When you call a JS function, and when that function
takes out an additional reference on the value, V8 "knows" about it.
It won't garbage-collect the value until there are no more references.

> }
>
> Do you need/want a HandleScope when you call the callback?
> What happens to argv in the example if you do use a new HandleScope?
>
>
> Thanks for the help!
>
> Cecil
Reply all
Reply to author
Forward
0 new messages