我希望我的C库能够多次调用JS函数。我使用Nan让它工作,但在将它转换为N-API/node-addon-api时遇到了问题。
如何保存JS回调函数并在以后从C中调用它?
以下是我使用Nan的情况:
Persistent<Function> r_log;
void sendLogMessageToJS(char* msg) {
if (!r_log.IsEmpty()) {
Isolate* isolate = Isolate::GetCurrent();
Local<Function> func = Local<Function>::New(isolate, r_log);
if (!func.IsEmpty()) {
const unsigned argc = 1;
Local<Value> argv[argc] = {
String::NewFromUtf8(isolate, msg)
};
func->Call(Null(isolate), argc, argv);
}
}
}
NAN_METHOD(register_logger) {
Isolate* isolate = info.GetIsolate();
if (info[0]->IsFunction()) {
Local<Function> func = Local<Function>::Cast(info[0]);
Function * ptr = *func;
r_log.Reset(isolate, func);
myclibrary_register_logger(sendLogMessageToJS);
} else {
r_log.Reset();
}
}如何使用node-addon-api执行等效操作?我见过的所有示例都会立即调用回调,或者使用AsyncWorker以某种方式保存回调。我不知道AsyncWorker是怎么做到的。
发布于 2019-01-29 23:33:23
我从the node-addon-api maintainers得到了一个答案,这使我找到了这个解决方案:
FunctionReference r_log;
void emitLogInJS(char* msg) {
if (r_log != nullptr) {
const Env env = r_log.Env();
const String message = String::New(env, msg);
const std::vector<napi_value> args = {message};
r_log.Call(args);
}
}
void register_logger(const CallbackInfo& info) {
r_log = Persistent(info[0].As<Function>());
myclibrary_register_logger(emitLogInJS);
}https://stackoverflow.com/questions/54295210
复制相似问题