2

我目前正在使用 C++ 编写一个 node.js 插件node-addon-api (Napi)。从我在不同的文档和教程中看到的,每个对象都必须扩展Napi::ObjectWrap才能被视为 js 对象。然后可以在js中调用构造函数。但是,如果我希望这个特定对象仅由另一个对象提供并将 js 构造函数设为私有怎么办?考虑到这种情况

class Provided: public Napi::ObjectWrap<Provided> {
public:
   // Init function for exports
   static Init(Napi::Env, Napi::Object exports);
   // what if I want my constructor to have a value instead of a CallbackInfo and only allow instantiation from c++ ?
   Provided(std::string value);
private:
   std::string m_value;
};

class MyProvider: public Napi::ObjectWrap<MyProvider> {
public:
   // Init function for exports
   static Init(Napi::Env, Napi::Object exports) {
      Napi::Function func = DefineClass(env, "provider", {InstanceMethod("getProvided", &MyProvider::GetProvided)});

      constructor = Napi::Persistent(func);
      constructor.SupressDestruct();

      exports.Set("Provider", func);
      return exports;
   }
   MyProvider(Napi::CallbackInfo const&): Napi::ObjectWrap<MyProvider>(info) {
       this->m_provided = Provided("my value");

   }
private:
   Provided m_provided;
   static Napi::FunctionReference constructor;
}

如何能够Napi::CallbackInfo在提供的构造函数中没有

4

1 回答 1

2

我的解决方案是使用data参数DefineClass来传递我的参数(在我的情况下只有一个,但我想你可以传递一个数组/向量/任何容器,只要你愿意)。然后我创建了一个“Provided”类的实例并返回它。但是一个例子比我的解释更有价值:

class Provided: public Napi::ObjectWrap<Provided> {
public:
   // Factory for a JavaScript class instance
   static Create(Napi::Env env, std::string &myString) {
      // Pass the argument(s) as last DefineClass argument
      Napi::Function func = DefineClass(env, "provided", {InstanceMethod("getString", &MyProvider::GetString)}, &myString);
   };
   Provided(const Napi::CallbackInfo &info) {
      // And get the c++ object back in the constructor.
      // It requires a cast as it goes through being a void pointer.
      myValue = *(std::string *)info.Data();
   };
private:
   std::string myValue;
   Napi::Value GetString(const Napi::CallbackInfo &info) {
      return Napi::String::New(info.Env(), myValue);
   };
};

class MyProvider: public Napi::ObjectWrap<MyProvider> {
public:
   // Init function for exports
   static Init(Napi::Env env, Napi::Object exports) {
      Napi::Function func = DefineClass(env, "provider", {InstanceMethod("getProvided", &MyProvider::GetProvided)});

      constructor = Napi::Persistent(func);
      constructor.SupressDestruct();

      exports.Set("Provider", func);
      return exports;
   }
   MyProvider(Napi::CallbackInfo const&): Napi::ObjectWrap<MyProvider>(info) {
      // Use the "Factory" to create an object instance.
      m_provided = Provided::Create(info.Env(), "my value");

   }
private:
   Provided m_provided;
   static Napi::FunctionReference constructor;
}
于 2021-08-30T22:11:44.097 回答