Return a Nan::ObjectWrap from another Nan::ObjectW

2019-05-06 23:26发布

问题:

I have two subclasses of Nan::ObjectWrap

class Zyre: public Nan::ObjectWrap {...}

class ZyreEvent: public Nan::ObjectWrap {...}

How can I return a ZyreEvent javascript object from a method in Zyre?

I have the following method, in which I create a ZyreEvent:

NAN_METHOD (Zyre::_recv) {
  Zyre *node = Nan::ObjectWrap::Unwrap <Zyre> (info.Holder ());
  ZyreEvent *zyre_event = new ZyreEvent (node->self);
  info.GetReturnValue().Set(zyre_event->Wrap(info.This()));
}

But I can't Wrap the zyre_event because Wrap is a protected member.

回答1:

If I understand correctly, you want to return from (subclass of) Nan::ObjectWrap's method instance of another (subclass of) Nan::ObjectWrap.

Note: I'm not experienced so this may have faults or be wrong. I've put my sources in brackets where are examples how it's is done I guess.

  1. Create static NewInstance method in a first class which receives pointer of itself (NewInstance)
  2. Use v8::External to wrap first class' C++ object and pass it as an argument for New with argc and argv to first class' constructor (using v8::External) (v8::External doc)
  3. Edit first class' New method and handle info.Length() == 1 && info[0]->IsExternal() case which is basically copy constructor in this case (copying passed pointer)
  4. Use ...::NewInstance() in second class to set return value