【发布时间】:2019-11-30 09:49:47
【问题描述】:
我正在使用节点 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);
我不知道为什么我不能持久化一个函数并在以后调用它而不会收到“分段错误”错误,有什么线索吗?
谢谢!
【问题讨论】:
-
您是否尝试过在调试模式下编译代码并在调试器中运行它?崩溃的回溯是什么? -- 如果没有 DevTools,你(大概)不会编写 JavaScript;不要在没有调试器的情况下编写 C++ ;-)
-
@jmrk 是的,但我没有看到任何东西,这是我第一次使用节点插件,所以我真的不知道我应该寻找什么,知道吗?
-
我看到当我的'updateCallback'回调被执行时,Isolate::GetCurrent() 为空,这可能是问题吗?
-
在检查回调的线程 id 后,它似乎与启动模块时设置回调的线程不同,这是线程不同的问题吗?
-
崩溃的回溯是什么?
标签: javascript c++ node.js v8