Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
686 views
in Technique[技术] by (71.8m points)

c++ - Calling callback from node.js native code

I'm writing an add-on for node.js using c++.

here some snippets:

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));
  }

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()

thanks in advice

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

There are docs here: http://nikhilm.github.io/uvbook/threads.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...