我有一个调用本机 C 库的节点 js 服务。原生库,不断重复触发事件。这些事件被传递给 C 回调函数。我的目标是从本机 C 回调中调用 Javascript 回调。
根据我的阅读,我正在使用 uv_async_init 和 uv_async_send 来实现这个目标。
我遇到的问题是我的本机 C 回调函数被多次调用,并且 uv_async_send 被多次调用,但传递给 uv_async_init 的函数仅在我的程序退出时被调用一次。
这是我的 C 代码:
==================================================== ===
#include "jsaudio.h"
#include <iostream>
using namespace v8;
static void recordAudioCallback(int index);
void asyncmsg(uv_async_t* handle);
Callback* cbPeriodic;
uv_async_t async;
uv_loop_t* loop;
NAN_METHOD(createEngine) {
std::cout << "==> createEngine\n" ;
}
void createAudioRecorder(const Nan::FunctionCallbackInfo<v8::Value>& info) {
std::cout << "==> createAudioRecorder\n";
}
void startRecording(const Nan::FunctionCallbackInfo<v8::Value>& info) {
std::cout << "==> startRecording\n";
cbPeriodic = new Callback(info[0].As<Function>());
loop = uv_default_loop();
uv_async_init(loop, &async, asyncmsg);
}
void asyncmsg(uv_async_t* handle) {
std::cout << "==> asyncmsg \n";
Nan::HandleScope scope;
v8::Isolate* isolate = v8::Isolate::GetCurrent();
Local<Value> argv[] = { v8::String::NewFromUtf8(isolate, "Hello world") };
cbPeriodic->Call(1, argv);
}
/* This my callback that gets called many times, by a native library*/
static void recordAudioCallback(int index) {
std::cout << "==> recordAudioCallback " << index << "\n";
uv_async_send(&async);
}
==================================================== ====
这是我的测试 node.js 代码,它调用了上面的本机代码
const jsAudio = new JsAudio({sampleRate: 48000, bufferSize: 8192})
function Test () {
jsAudio.createEngine();
jsAudio.createAudioRecorder();
jsAudio.startRecording(function(error, result) {
if (error) {
console.log('startRecording failed: ' + error);
} else {
console.log('startRecording result: ' + result);
}
});
}
Test();
var waitTill = new Date(new Date().getTime() + 3 * 1000);
while(waitTill > new Date()){}
jsAudio.shutdown();
console.log('program exit...');
==================================================== ========
这是输出:
==> createEngine
==> createAudioRecorder
==> startRecording
==> recordAudioCallback 0
==> recordAudioCallback 1
==> recordAudioCallback 0
==> recordAudioCallback 1
==> recordAudioCallback 0
==> shutdown
program exit...
==> asyncmsg
startRecording failed: Hello world
==================================================== =========
为什么 asyncmsg 只被调用一次!即使 recordAudioCallback 被多次调用!程序退出后为什么会调用它!
任何帮助表示赞赏。