简体   繁体   中英

Napi::ObjectWrap: is a destructor called and how?

I'm building an addon for node.js thanks to the node-addon-api .

Each of my 'traditionals' C++ classes is wrapping a C object. Then my Napi::ObjectWrap classes wrap these C++ objects.

my_object -> MyObject -> Napi::ObjectWrap<MyObjectWrapper>

The MyObjectWrapper instance contains a reference to a MyObject instance, that contains a reference to a my_object instance. As, the C object needs to be freed, I was thinking the destructor of MyObject would do the job, but it's never called by the wrapper.

I'm fairly new to node-addon-api and I'm not sure to understand the garbage collector like needed.

What I would like to know is when and how the wrapper is destroyed, and if passing null to the object on the Javascript side has any effect. Any clue on this would be highly appreciated.

I'm a node-addon-api beginner like you.I find the answer in Github.

Here's the link Destructor not called

My understanding is that V8 GC run when memory will become insufficient. So if you want to call destructor that belong to an ObjectWrapper of c++ instance, you should force the gc run.

The sample code is as follows:

var createObject = require('bindings')('addon'); //

function forceGC() {
    if (global.gc) {
      global.gc();
    } else {
      console.warn('No GC hook! Start your program as `node --expose-gc ./addon.js`.');
    }
  }

var obj = createObject(10); //creat ObjectWrapper from c++ to V8 
console.log(obj);
console.log( obj.plusOne() ); // 11
console.log( obj.plusOne() ); // 12
console.log( obj.plusOne() ); // 13
obj=null;
forceGC();//after forceGC ,the c++ destructor function will call

Hope this helps

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