简体   繁体   中英

Returning c++ object instance with node-addon-api

In javascript the code i trying to run is

const Element = require("element.node");
let element = new Element();
console.log(element.parent); // null
element.parent = element;
console.log(element.parent === element); // should be true

So in the cpp Element class i have

void Element::SetParent(const Napi::CallbackInfo &info, const Napi::Value &value) {
    this->parent = Element::Unwrap(info[0].As<Napi::Object>());
}

but i don't know how to implement the GetParent method, this->parent has the correct pointer but all the exemples i find on internet create a new instance of c++ Element calling js constructor to have an Napi::Object

Can i call some method to reverse Element::Unwrap ?

Like

Napi::Value Element::GetParent(const Napi::CallbackInfo &info) {
    Napi::Env env = info.Env();
    if (this->parent == NULL) {
        return env.Null();
    }
    return Napi::Object::Wrap(this->parent);
}

Do not unwrap the JS object. Keep a shared pointer to a persistent reference to the JS object:

this->parent =
  std::make_shared<Napi::Reference<Napi::Object>>(Napi::Persistent(info[0].As<Napi::Object()>));

Using a shared pointer will take care of destroying the persistent reference when the object is destroyed - otherwise you will get a memory leak.

this->parent should be a Napi::Reference<Napi::Object>

or

a much easier solution is to delegate this operation to the JS glue - all serious addons have a JS wrapper that performs such operations that are much easier in JS than in C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM