简体   繁体   English

Napi::ObjectWrap: 是一个析构函数,如何调用?

[英]Napi::ObjectWrap: is a destructor called and how?

I'm building an addon for node.js thanks to the node-addon-api .多亏了node-addon-api ,我正在为 node.js 构建一个插件。

Each of my 'traditionals' C++ classes is wrapping a C object.我的每个“传统”C++ 类都包装了一个 C 对象。 Then my Napi::ObjectWrap classes wrap these C++ objects.然后我的 Napi::ObjectWrap 类包装这些 C++ 对象。

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. MyObjectWrapper 实例包含对 MyObject 实例的引用,该实例包含对 my_object 实例的引用。 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.因为,需要释放 C 对象,我认为 MyObject 的析构函数可以完成这项工作,但包装器从未调用过它。

I'm fairly new to node-addon-api and I'm not sure to understand the garbage collector like needed.我是 node-addon-api 的新手,我不确定是否了解所需的垃圾收集器。

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.我想知道包装器何时以及如何被销毁,以及是否将 null 传递给 Javascript 端的对象有任何影响。 Any clue on this would be highly appreciated.对此的任何线索将不胜感激。

I'm a node-addon-api beginner like you.I find the answer in Github.我和你一样是 node-addon-api 初学者。我在 Github 中找到了答案。

Here's the link Destructor not called这是未调用的链接析构函数

My understanding is that V8 GC run when memory will become insufficient.我的理解是 V8 GC 在内存不足时运行。 So if you want to call destructor that belong to an ObjectWrapper of c++ instance, you should force the gc run.所以如果你想调用属于 C++ 实例的 ObjectWrapper 的析构函数,你应该强制 gc 运行。

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希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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