在本机节点的回调中调用回调

Calling callback inside callback in native Node

我是一个 node 和 C++ 新手所以要宽容。

我正在编写本机节点插件。

我的插件启动了网络摄像头流(使用 UVC 库),我希望每一帧都可用于节点。

我的 CC 插件可以做类似的事情

uvc_start_streaming(devh, &ctrl, frameProcess, (void *) &args, 0)

其中:

每个新帧都会调用 C++ 回调,我想简单地打印类似 "new frame received" 的内容,所以我的 C++ 就像:

void frameProcess(uvc_frame_t *frame, void *ptr) {
  const FunctionCallbackInfo<Value> args = *((const FunctionCallbackInfo<Value>*)(ptr));
  Isolate* isolate = args.GetIsolate();

  Local<Function> cb = Local<Function>::Cast(args[0]);  
  const unsigned argc = 1;
  Local<Value> argv[argc] = { String::NewFromUtf8(isolate, "new frame received") };
  cb->Call(Null(isolate), argc, argv);

}

void testStreaming (const FunctionCallbackInfo<Value>& args) {
    ...
    res = uvc_start_streaming(devh, &ctrl, frameProcess, (void *) &args, 0);
    puts("Streaming...");
    Sleep(10000); /* stream for 10 seconds */
    uvc_stop_streaming(devh);
    puts("Done streaming.");
    ...
}

...
NODE_SET_METHOD(exports, "testStreaming", testDevice);

我的js是这样的:

'use strict';
var uvc = require('../build/Release/binding')
uvc.testStreaming(
  function (x) {
    console.log(x)
  }
)

问题是当程序到达 cb->Call 时,节点退出时没有任何消息或错误。

如果我评论 cb->Call row the program 运行 10 秒(连续调用),然后退出。

但是如果我取消注释 cb->立即调用程序退出。

您的 frameProcess() 函数应该在 Node.js 线程中调用 v8::Function 回调,参见