9

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?

4

1 回答 1

1

String::New("foo")将在堆上分配一些东西并返回一个句柄,因此您需要以某种方式释放此句柄引用的内存。如果您将它们附加到HandleScopev8 上,那么一旦所有引用计数为零,就会为您执行此操作。

本地句柄保存在堆栈上,并在调用适当的析构函数时被删除。这些句柄的生命周期由句柄范围确定,该范围通常在函数调用开始时创建。当句柄范围被删除时,垃圾收集器可以自由地释放句柄范围内以前由句柄引用的那些对象,前提是它们不再可以从 JavaScript 或其他句柄访问。

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

于 2014-01-24T12:29:43.050 回答