Вопрос

Suppose I have some asm.js code, probably created by emscripten. Suppose it has some kind of rather large heap allocated structure, which gets returned by a asm.js function as a pointer that is picked up by some JavaScript library to be wrapped in a nice JavaScript object. Fine so far.

But what happens if that object goes out of scope and gets garbage collected. Right now, the asm.js code has no way of knowing about that, so the memory of the structure will remain allocated, causing a memory leak.

Is there some way to add a finalizer to a JavaScript object from within JavaScript?

Such a finalizer could be used to deallocate the memory in asm.js, thus avoiding the memory leak. So far I couldn't find a documented i.e. portable way to achieve this, but perhaps I've been looking in the wrong places.

Это было полезно?

Решение

The simple answer is that there is no support for this.

Since asm.js code needs to manage its own memory, everything that interacts with objects stored on the asm side need to respect the memory manager that asm uses rather than the memory manager that the browser uses. The best that you can do is to explicitly call a method on any object referencing internal asm memory whenever you create or destroy a reference to it.

Другие советы

Coming back to this question, I found another answer pointing out that there is a specification for weak references and finalization which some browsers implement. The central component for finalization is FinalizationRegistry.

So depending on which browsers you target, this may be possible now. If you need to support browsers without this feature, using explicit release calls, it might be possible to use the finalizers where supported to detect memory leaks (i.e. objects not explicitly released in JavaScript code) and let the developer know so they can fix this.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top