我希望我的 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 是怎么做到的。
最佳答案
我从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);
}
关于node.js - 如何使用 node-addon-api 保存回调供以后使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54295210/