我正在使用节点12和NAN开发一个更小的节点插件。当我尝试保存一个JS回调以便稍后执行时,我遇到了一个问题。
这是c++代码(简化版)
#include <nan.h>
static MyObject *object;
Nan::Persistent<v8::Function> reloadCallback;
class Example : public Nan::ObjectWrap
{
public:
static NAN_MODULE_INIT(Init)
{
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->InstanceTemplate()->SetInternalFieldCount(1);
constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked());
}
static NAN_METHOD(NewInstance)
{
v8::Local<v8::Function> cons = Nan::New(constructor());
const int argc = 1;
v8::Local<v8::Value> argv[1] = {info[0]};
info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
}
private:
static void updateCallback()
{
// HERE is the place where I want to call the JS callback
if (!reloadCallback.IsEmpty())
{
printf("Callback set");
}
}
static NAN_METHOD(New)
{
if (info.IsConstructCall())
{
// This is the JS callback, if I execute if right here (when JS init this module) all works well, with the Nan:: Callback
v8::Local<v8::Function> cbFunc = v8::Local<v8::Function>::Cast(info[0]);
// Nan::Callback cb(cbFunc);
// cb.Call(0, NULL);
// But, if I persist it here and try to recover later (don't know when this will be called, could be at any time) I have a Segmentation Error
// reloadCallback.Reset(cbFunc);
try
{
// This object will call this updateCallback function with something happens
object->setCallbackInfo(updateCallback, NULL);
}
catch (Error &e)
{
Nan::ThrowError("Error");
}
}
else
{...}
}
static inline Nan::Persistent<v8::Function> &constructor()
{
static Nan::Persistent<v8::Function> my_constructor;
return my_constructor;
}
};
NAN_MODULE_INIT(Init)
{
Example::Init(target);
Nan::Set(target,
Nan::New<v8::String>("init").ToLocalChecked(),
Nan::GetFunction(
Nan::New<v8::FunctionTemplate>(Example::NewInstance))
.ToLocalChecked());
}
NODE_MODULE(module, Init)JS代码
const example = require('bindings')('module');
function log(a) {
console.log('Hi from JS', a);
}
example.init(example, log);我不知道为什么我不能持久化一个函数并在以后调用它,而不会得到一个“分段错误”错误,有什么线索吗?
谢谢!
发布于 2019-12-04 16:43:12
修复了使用libuv及其uv_async_init和使用uv_async_send方法的问题。
https://stackoverflow.com/questions/59114971
复制相似问题