In V8, how would I remove wrapped C++ objects after their JavaScript counterparts are garbage-collected?
Asked Answered
A

1

6

Let's say I have the code provided in this tutorial.

How would I modify this so that the Point C++ object that is created has its destructor called and is deleted from memory when the GC for V8 destroys the JavaScript wrapper?

Autecology answered 1/1, 2011 at 7:20 Comment(1)
K
8

You want to create a Persistent handle and make it weak (v8::Persistent::MakeWeak(data, cb)). In the callback you can delete the C++ object. As usual with a garbage collector, the exact time at which weak-reachability will be determined is dependent on when GC is performed. Native resources may therefore be freed much later than you expect. You can inform V8 about the amount of native resources you are holding (v8::AdjustAmountOfExternalAllocatedMemory).

node's "ObjectWrap" encapsulates the bidirectional native/JS object mapping and weak callback: https://github.com/ry/node/blob/master/src/node_object_wrap.h

Kikuyu answered 9/1, 2011 at 20:24 Comment(1)
Make sure you call Dispose on the Persistent Handle or you'll get a memory leak. Just spent a few hours tracking that down in my code, eventually used the ClearWeak(), Dispose(), Clear() calls like the Object wrap destructor uses and it fixed it.Sir

© 2022 - 2024 — McMap. All rights reserved.