1

我正在开发 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 参数,我无法弄清楚如何包装对象。

帮助?

4

1 回答 1

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);
  }
};
于 2015-11-24T17:13:05.007 回答