问题描述
我正在使用 C++ 为 node.js 编写附加组件.
I'm writing an add-on for node.js using c++.
这里有一些片段:
class Client : public node::ObjectWrap, public someObjectObserver {
public:
void onAsyncMethodEnds() {
Local<Value> argv[] = { Local<Value>::New(String::New("TheString")) };
this->callback->Call(Context::GetCurrent()->Global(), 1, argv);
}
....
private:
static v8::Handle<v8::Value> BeInitiator(const v8::Arguments& args) {
HandleScope scope;
Client* client = ObjectWrap::Unwrap<Client>(args.This());
client->someObject->asyncMethod(client, NULL);
return scope.Close(Boolean::New(true));
}
static v8::Handle<v8::Value> SetCallback(const v8::Arguments& args) {
HandleScope scope;
Client* client = ObjectWrap::Unwrap<Client>(args.This());
client->callback = Persistent<Function>::New(Handle<Function>::Cast(args[0]));
return scope.Close(Boolean::New(true));
}
我需要将一个 javascript 函数保存为回调以供稍后调用.Client 类是另一个对象的观察者,应该从 onAsyncMethodEnds 调用 javascript 回调.不幸的是,当我调用函数BeInitiator"时,我在回调 Call() 之前收到Bus error: 10"错误
I need to save a javascript function as callback to call it later. The Client class is an observer for another object and the javascript callback should be called from onAsyncMethodEnds. Unfortunately when I call the function "BeInitiator" I receive "Bus error: 10" error just before the callback Call()
感谢建议
推荐答案
您不能从另一个线程->Call
.JavaScript 和 Node 是单线程的,尝试从另一个线程调用一个函数相当于尝试同时运行两个 JS 线程.
You cannot ->Call
from another thread. JavaScript and Node are single threaded and attempting to call a function from another thread amounts to trying to run two threads of JS at once.
您应该重新编写代码以避免这样做,或者您应该阅读 libuv
的线程库.它提供了uv_async_send
,可用于从单独的线程触发主JS循环中的回调.
You should either re-work your code to not do that, or you should read up on libuv
's threading library. It provides uv_async_send
which can be used to trigger callback in the main JS loop from a separate thread.
这里有文档:http://nikhilm.github.io/uvbook/threads.html
这篇关于从 node.js 本机代码调用回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!