首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Node C++ addon持久化JS回调供以后使用

Node C++ addon持久化JS回调供以后使用
EN

Stack Overflow用户
提问于 2019-11-30 17:49:48
回答 1查看 255关注 0票数 0

我正在使用节点12和NAN开发一个更小的节点插件。当我尝试保存一个JS回调以便稍后执行时,我遇到了一个问题。

这是c++代码(简化版)

代码语言:javascript
运行
复制
#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代码

代码语言:javascript
运行
复制
const example = require('bindings')('module');
function log(a) {
    console.log('Hi from JS', a);
}
example.init(example, log);

我不知道为什么我不能持久化一个函数并在以后调用它,而不会得到一个“分段错误”错误,有什么线索吗?

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2019-12-04 16:43:12

修复了使用libuv及其uv_async_init和使用uv_async_send方法的问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59114971

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档