Javascript 节点C++;插件持久化JS回调供以后使用
我正在使用node 12和NAN开发一个小节点插件。当我试图保存JS回调以便稍后执行时,我遇到了一个问题Javascript 节点C++;插件持久化JS回调供以后使用,javascript,c++,node.js,v8,Javascript,C++,Node.js,V8,我正在使用node 12和NAN开发一个小节点插件。当我试图保存JS回调以便稍后执行时,我遇到了一个问题 这是C++代码(简化版) 我不知道为什么我不能持久化一个函数,并在以后调用它时不会出现“分段错误”,有什么线索吗 谢谢 修复了使用及其uv\u async\u init和使用uv\u async\u send方法的问题。您是否尝试过在调试模式下编译代码并在调试器中运行它?坠机的背景是什么?--如果没有DevTools,您(大概)不会编写JavaScript;不要编写没有调试器的C++;jmr
这是C++代码(简化版)
我不知道为什么我不能持久化一个函数,并在以后调用它时不会出现“分段错误”,有什么线索吗谢谢 修复了使用及其uv\u async\u init和使用uv\u async\u send方法的问题。您是否尝试过在调试模式下编译代码并在调试器中运行它?坠机的背景是什么?--如果没有DevTools,您(大概)不会编写JavaScript;不要编写没有调试器的C++;jmrk是的,我看到了,但我没有看到任何东西,这是我第一次使用节点加载项,所以我不知道我应该寻找什么,知道吗?我看到当执行“updateCallback”回调时,Isolate::GetCurrent()为空,这可能是问题吗?在检查回调的线程id后,它似乎与启动模块时设置回调的线程不同,这是一个具有不同线程的问题吗?崩溃的回溯是什么?
#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)
const example = require('bindings')('module');
function log(a) {
console.log('Hi from JS', a);
}
example.init(example, log);