内存管理

翻译不完整。 请帮助我们翻译这篇文章!

内存管理

If JS code creates a structure or an array, that memory will be valid as long as the JS object stays alive. Pointers to that memory must be carefully managed to make sure the underlying memory is still referenced.

When binary code hands back a pointer/handle to allocated memory, the JS code must make sure to free that memory with the correct allocator. It is usually best to expose a freeing function from the binary.

保持 objects 活着

The following js-ctypes objects will hold references to objects, keeping them alive. This is not an exhaustive list, but will help you to  understand memory management and how it affects your use of js-ctypes:

  • A function or static data declared using the declare() method will hold that library alive.
  • CType will hold referent CType objects alive.
  • CData will hold referent CData objects alive, under specific circumstances. For example, a CData object produced by accessing a field of a structure or the internals of an array will hold the referent objects alive.

什么不保持 objects 活着

It's important to note that getting direct access to the contents of a CData object using address()addressOfElement(), or contents, will result in a CData object that does not hold its referent alive. Be sure to hold an explicit reference so that the referent object doesn't get into garbage collection, before you're done using it.

闭包

You also need to be sure to retain references to any JavaScript code that native code may call back into. This should be obvious, but is important enough to be worth stating explicitly.

有疑问时, malloc()

When you need to keep data around, you can use malloc() to allocate it directly. This bypasses JavaScript's memory management and lets you handle memory management yourself.