我目前正在使用node.js在c++中使用node-addon-api (Napi)编写一个node-addon-api (Napi)插件。从我在不同的文档和教程中看到的情况来看,每个objet都必须扩展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
发布于 2021-08-30 22:11:44
我的解决方案是使用data参数DefineClass来传递我的参数(在我的例子中,只有一个,但我想您可以通过任意数量的容器传递数组/向量/任何容器)。然后,我创建了一个“提供”类的实例并返回它。但有一个例子比我的解释更有价值:
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;
}https://stackoverflow.com/questions/65188873
复制相似问题