我正在尝试注册一个 JavaScript 回调函数,以便稍后从 C++ 类调用。我正在使用 nbind制作一个 node.js 插件。这是我编写的一些示例代码,其中包含一些需要完成相同事情的更复杂的代码:
C++代码(testing.cc):
#include "nbind/api.h"
#include <string>
#include <iostream>
class Test
{
nbind::cbFunction *callback;
public:
Test() {}
//this dummy var is only here so that doCallback() will be recognized as a function
void doCallback(int dummyVar)
{
std::cout << "Calling Javascript callback" << std::endl;
//call javascript code
if (callback != nullptr)
{
(*callback)("Hi there!\n");
}
return;
}
void enrollCallback(nbind::cbFunction &cb)
{
callback = &cb;
return;
}
};
#include "nbind/nbind.h"
NBIND_CLASS(Test) {
construct<>();
method(doCallback);
method(enrollCallback);
method(unenrollCallback);
}
JavaScript 代码(test.js):
var nbind = require('nbind');
function printMessage(message) {
console.log(message);
}
var lib = nbind.init().lib;
var test = lib.Test();
test.enrollCallback(printMessage);
try{
test.doCallback(11);
} catch(err) {
console.log(err);
}
当我在命令行中运行上面的代码时,我根本没有得到任何输出。当我像这样运行代码:node inspect test.js
并输入继续命令时,调用回调函数时出现以下错误:
Error: read ECONNRESET
at _errnoException (util.js:992:11)
at TCP.onread (net.js:618:25)
当我单步执行我的程序时,控制台出现以下错误:
TypeError: test.doCallback is not a function
at Object.<anonymous> (C:\Users\mrcole\Desktop\testy\test.js:22:10)
at Module._compile (module.js:649:14)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:191:16)
at bootstrap_node.js:612:3
我哪里出错了,为什么 Node 行为不一致?
最佳答案
为了回答我自己的问题,不要使用 nbind 以这种方式调用 Node JavaScript 回调函数。这是一个异步调用(如果我错了请纠正我)并且截至 2018 年 6 月,nbind 不支持异步回调。
一个好的替代方法是实现 AsyncWorker classes provided by NAN 之一.
下面是一些示例代码:
class MyAsyncWorker : public Nan::AsyncProgressWorkerBase<T>
{
public:
MyAsyncWorker(Nan::Callback *callback_, const char *resource_name = "My Async Worker")
: AsyncProgressWorkerBase(callback_, resource_name)
{
}
~MyAsyncWorker()
{
}
//Do work, or process notifications here
void Execute(const ExecutionProgress &progress)
{
//do work. when you have something to report,
//call ExecutionProgress::Send( T * data, size_t count) to eventually call
//the HandleProgressCallback function.
}
//Call JavaScript callback from this function
void HandleProgressCallback(T *data, size_t count)
{
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = {
//initialize your data to passback to callback here
};
callback->Call(count,argv,async_resource);
}
//This is called when you are done executing
virtual void HandleOKCallback()
{
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = {
//Prepare final values to be returned
};
callback->Call(1,argv,async_resource);
}
};
关于javascript - 从 C++ 代码调用 JavaScript 回调函数抛出错误 - nbind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50862829/