我很难理解如何正确使用 HandleScope和 EscapableHandleScope 。例如,来自this Node example :
MyObject::MyObject(const Napi::CallbackInfo& info) : Napi::ObjectWrap<MyObject>(info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
this->val_ = info[0].As<Napi::Number>().DoubleValue();
};
为什么在这种情况下我们需要创建一个新的 HandleScope?以及来自this other example :
Napi::Object CreateObject(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::Object obj = Napi::Object::New(env);
obj.Set(Napi::String::New(env, "msg"), info[0].ToString());
return obj;
}
为什么这里不需要它?
另外,我没有找到任何使用 EscapeableHandleScope 的示例,什么时候需要这个?
最佳答案
以下内容似乎适用于 nan、N-API 和 node-addon-api:
[Handle Scope] is an abstraction used to control and modify the lifetime of objects created within a particular scope. In general, N-API values are created within the context of a handle scope. When a native method is called from JavaScript, a default handle scope will exist. If the user does not explicitly create a new handle scope, N-API values will be created in the default handle scope. For any invocations of code outside the execution of a native method (for instance, during a libuv callback invocation), the module is required to create a scope before invoking any functions that can result in the creation of JavaScript values.
来源:https://nodejs.org/api/n-api.html#n_api_napi_handle_scope
这意味着在给出的示例中,因为两者都期望 const Napi::CallbackInfo& info
很明显,两者都是直接从 JavaScript 调用的,因此它们已经具有 JS 运行时提供的作用域——只有当您想自己执行内存管理,或者您的代码独立执行时,才需要创建作用域的额外调用JS 引擎(例如计时器、来自 JS 代码以外的回调等)
关于node.js - 了解 Node 插件 API (N-API) HandleScope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54187588/