Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct use of HandleScope in Asynchronous Addon

Tags:

node.js

v8

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?

   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?
}

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?

like image 762
snowballhg Avatar asked May 22 '13 20:05

snowballhg


1 Answers

String::New("foo") will allocate something on heap and return a handle, so you need to free the memory referenced by this handle some how. If you attach them to a HandleScope v8 will do that for you once all references are counted to zero.

Local handles are held on a stack and are deleted when the appropriate destructor is called. These handles' lifetime is determined by a handle scope, which is often created at the beginning of a function call. When the handle scope is deleted, the garbage collector is free to deallocate those objects previously referenced by handles in the handle scope, provided they are no longer accessible from JavaScript or other handles.

https://developers.google.com/v8/embed

like image 90
exebook Avatar answered Nov 04 '22 21:11

exebook