从C ++线程调用时JS回调失败(nodejs插件)

时间:2019-09-16 00:38:59

标签: c++ node.js node-addon-api

我创建了一个nodejs插件,该插件应该执行回调(作为参数传递的javascript函数)。由于某些原因,当行“ v8 :: Locker locker(isolate);”时到达后,什么也没发生,似乎只是挂在那了。有什么我想念的或做错的吗?我安装了节点10.16.3(32位)。

JS函数

  const callbackaddon = require("../build/Release/callbackaddon");
...
  app.CheckApiConnection = function() {
    callbackaddon(msg => {
      console.log(msg);
    });
  };

cc文件

#include <node.h>
#include <iostream>
#include <memory>
#include <thread>
#include <mutex>
#include <string>
#include <functional>

using namespace std;
using namespace v8;

std::recursive_mutex m_spectrumMutex;

void Listener(const FunctionCallbackInfo<Value> &args, Isolate *isolate)
{
    lock_guard<recursive_mutex> lock(m_spectrumMutex);
    // Isolate *isolate = args.GetIsolate();
    cout << "Isolate init: " << isolate << endl;
    Local<Context> context = isolate->GetCurrentContext();
    cout << "Context init" << endl;
    Local<Function> cb = Local<Function>::Cast(args[0]);
    cout << "Callback init" << endl;
    const unsigned argc = 1;

    Local<Value> argv[argc] = {
        String::NewFromUtf8(isolate,
                            "hello world from callback",
                            NewStringType::kNormal)
            .ToLocalChecked()};

    cout << "Hello world II" << endl;

    v8::Locker locker(isolate);
    HandleScope scope(isolate);

    cb->Call(context, Null(isolate), argc, argv).ToLocalChecked();
}

void RunCallback(const FunctionCallbackInfo<Value> &args)
{
    Isolate *isolate = args.GetIsolate();
    cout << "Isolate init: " << isolate << endl;
    auto cbfunction = std::bind(&Listener, args, isolate);
    thread action(cbfunction);
}

void Init(Local<Object> exports, Local<Object> module)
{
    NODE_SET_METHOD(module, "exports", RunCallback);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, Init)

绑定gyp文件

...
       {
           "target_name": "callbackaddon",
           "sources": [ "addons/callbackTest.cc" ],
           "include_dirs" : [ 
                "<!(node -e \"require('nan')\")"
            ]
       },
...

我希望调用JS函数,并且“ hello world from callback”消息会出现在控制台中。我正在Visual Studio Code中进行这项工作。

0 个答案:

没有答案