Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
682 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...