如何从NanAsyncWorker返回一个新对象?

时间:2015-05-01 18:01:50

标签: c++ node.js v8 node-modules node.js-addon

我正在使用node.js / io.js本机插件,我需要从异步回调中创建一个新的本机对象。

使用nan助手,我有一些看起来像:

class MyObject : public node::ObjectWrap
{ /* definition */ };

class MyWorker : public NanAsyncWorker
{
  bool varForMyObject;
  virtual void Execute() {/* do stuff and sets varForMyObject */}

  virtual void HandleOKCallback() {
    NanScope();

    MyObject* obj = new MyObject(varForMyObject);

    Local<Value> argv[] = {
      NanNull(),
      obj // ???
    };

    callback->Call(2, argv);
  }
};

我无法弄清楚如何在不访问args参数的情况下包装对象。

帮助?

1 个答案:

答案 0 :(得分:3)

您应该手动创建javascript对象,例如:

//some_class.h

class SomeClass {
public:
    std::string id;
    int value;
    SomeClass() {};
    SomeClass(std::string id, int value): id(id), value(value) {};

    static SomeClass *unpack(v8::Isolate *isolate, const v8::Local<v8::Object> object) {
        using namespace v8;

        SomeClass *p = new SomeClass();
        Local<Value> _id = object->Get(String::NewFromUtf8(isolate, "id"));

        String::Utf8Value utf8String(_id);
        p->id = std::string(*utf8String);
        p->value = static_cast<int>(object->Get(String::NewFromUtf8(isolate, "value"))->NumberValue());

        return p;
    }

    static v8::Local<v8::Object> pack(v8::Isolate *isolate, const SomeClass *object) {
        using namespace v8;
        Local<Object> obj = Object::New(isolate);

        obj->Set(String::NewFromUtf8(isolate, "id"), String::NewFromUtf8(isolate, object->id.c_str()));
        obj->Set(String::NewFromUtf8(isolate, "value"), Integer::New(isolate, object->value));

        return obj;
    };
}

然后在你的工作人员中:

class MyObject : public node::ObjectWrap
{ /* definition */ };

class MyWorker : public NanAsyncWorker
{

  virtual void Execute() {/* do stuff and sets varForMyObject */}

  virtual void HandleOKCallback() {
    NanScope();

   SomeClass *c = new SomeClass("id", 123);


    Local<Value> argv[] = {
      NanNull(),
      SomeClass::pack(v8::Isolate::GetCurrent(), c)
    };

    callback->Call(2, argv);
  }
};