Is there a way to automatically manage memory allocated by native code with js-ctypes?
I've inherited a Firefox add-on which badly needs an update to the new Firefox 4+ line. I finally have some time to work on it, but it turns out that this add-on includes a native portion compiled as an XPCOM component, and XPCOM components are now strongly discouraged. Since I really don't want to recompile my binaries every time a new major version is out, I'm looking into moving to js-ctypes.
Since the binary library is really quite small and simple, it doesn't seem like much of a trouble, but there's one thing that bothers me: since XPCOM objects were (typically) implemented as C++ objects, they had their destructor automatically called whenever the JavaScript wrapper object was garbage-collected. You didn't have to manage native resources manually in your JavaScript code.
Ideally, I would like to have equivalent functionality with js-ctypes. Since js-ctypes is more low-level than XPCOM it doesn't support objects directly, but I wonder if there's a way I could create by myself a wrapper object, and somehow get a notification when its being garbage-collected. I know that pure JavaScript has no concept of destructors, 开发者_开发技巧but maybe there's still a way I can do it in Firefox.
Unfortunately for you, it's an important concept in JavaScript that you cannot observe garbage collection (at least not from JavaScript itself). The only place where you have destructor-like functionality is XBL. In other words, you could define a XUL element that would serve as your wrapper object (similar to how <stringbundle>
serves as a wrapper for the localization API). Your XBL binding for that element should provide the necessary methods and call js-ctypes internally. And when the element is discarded (XBL destructor runs) you can clean up and release memory.
This assumes of course that you can work with XUL elements in the first place. If your code doesn't run in a window then IMHO you are out of luck - it's back to manual object tracking to discover the moment when the object is no longer used.
精彩评论