Nan Nodejs C ++使用ObjectWrap定义嵌套的对象结构

时间:2018-10-03 12:35:37

标签: c++ node.js prototype javascript-objects v8

当前,我正在使用native abstactions for nodejs进行C ++ NodeJS扩展。一切工作正常且编译良好,我能够定义Nan::SetPrototypeMethod()Nan::DefineOwnProperty()并在JavaScript中使用它们。由于在该对象上定义了大量功能和属性,因此我想在该js对象上实现一个嵌套结构,让用户如下使用该对象

const obj = new MyObject();
obj.directFunction(); // working

obj.subclass.childFunction();

我的C ++扩展如下。入口点是 addon.cc

#include <nan.h>
#include "myAddon.h"

NAN_MODULE_INIT(InitAll) {
  MyAddon::Init(target);
}

NODE_MODULE(addon, InitAll)

myAddon.h

#ifndef MYADDON_H
#define MYADDON_H

#include <nan.h>

#include "subClass.h"


class MyAddon: public Nan::ObjectWrap {
  public:
    static NAN_MODULE_INIT(Init);

  private:
    static NAN_METHOD(New); //constructor
    static NAN_METHOD(directFunction);
    MyAddon();
};

myAddon.cc 中的 Init 函数看起来像

NAN_MODULE_INIT(MyAddon::Init) {
  auto cname = Nan::New("MyAddon").ToLocalChecked();
  auto ctor = Nan::New<v8::FunctionTemplate>(New);
  auto ctorInst = ctor->InstanceTemplate();

  ctor->SetClassName(cname);
  ctorInst->SetInternalFieldCount(1);

  Nan::SetPrototypeMethod(ctor, "directFunction", directFunction);

  // Working
  Nan::SetPrototypeTemplate(ctor, "subclass", Nan::New<v8::Object>());

  // Trying to bind another class to "subclass" does not work
  Nan::SetPrototypeTemplate(ctor, "subclass", SubClass);

  // Also tested SubClass in a similar way with NAN_MODULE_INIT(Init) and NAN_METHOD(New) functions and use
  SubClass::Init(ctor)
  // which leads to
  // cannot convert from 'v8::FunctionTemplate *' to 'v8::Object *volatile '

  Nan::Set(target, cname, Nan::GetFunction(ctor).ToLocalChecked());
}

subClass.h 继承了Nan::ObjectWrap并看起来类似于

#ifndef SUBCLASS_H
#define SUBCLASS_H

#include <nan.h>

class SubClass : public Nan::ObjectWrap {
  private:
    // same as: static NAN_METHOD(childFunction)
    static void childFunction(const Nan::FunctionCallbackInfo<v8::Value>& info);

  public:
    SubClass(const Nan::FunctionCallbackInfo<v8::Value>& info);
};

#endif

我还测试了类似于MyAddon的SubClass,其中包括New和Init方法,但均无效。你有什么想法或建议吗?谢谢,加油!

0 个答案:

没有答案