I'm working on a littler node addon using node 12 and NAN.
(我正在使用节点12和NAN开发一个littler节点插件。)
I've an issue when I try to save a JS callback to execute later.(我尝试保存JS回调以便稍后执行时遇到问题。)
This is the c++ code (simplified version)
(这是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)
The JS code
(JS代码)
const example = require('bindings')('module');
function log(a) {
console.log('Hi from JS', a);
}
example.init(example, log);
I don't know why I can't persist a function and call it later without getting a 'Segmentation Fault' error, any clues?
(我不知道为什么我不能持久保存一个函数,以后再调用它而没有收到“ Segmentation Fault”错误,有什么线索吗?)
Thanks!
(谢谢!)
ask by Sergio translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…