daminetreg / js-bind

js::bind makes any C++ function, member function or lambda as a Javascript callback.
Boost Software License 1.0
22 stars 9 forks source link

Memory management #2

Open mmarczell-graphisoft opened 2 years ago

mmarczell-graphisoft commented 2 years ago

What is the memory management approach of this library? Are the C++ callbacks freed? Can I free them explicitly? This is important because they might be holding onto e. g. heavyweight objects through capture.

daminetreg commented 2 years ago

It's based on embind emscripten::val, hence if you stop reffering it from JS or from C++ it gets destroyed :

clickme_btn.set("onclick", js::bind(onclick, _1));

js::bind creates an std::function object managed by an emscripten::val referring to the onclick function/lambda. emscripten::val is like a shared_ptr between 2 worlds C++ and JS. It has a reference count and if nobody uses it anymore it gets deleted.

In this case if I change the "onclick" event handler of clickme_btn to something else the previous std::function should get deleted (as soon as JS garbage collection kicks in, as the reference is kept by an object in the JS space).