Open Bug 688797 Opened 13 years ago Updated 2 years ago

Add free()-on-finalize bit to CData and CType instances

Categories

(Core :: js-ctypes, defect)

defect

Tracking

()

People

(Reporter: kmag, Unassigned)

References

(Blocks 1 open bug)

Details

Currently malloc-allocated data from external functions need to be explicitly managed by JavaScript code. Since this is alien to the typical JavaScript programmer's mindset, I expect it to be a fair source of leaks. It would be useful if we were able to set a bit on these objects so that their memory was managed in the same way as JS-allocated CTypes objects. And, in particular, it would be useful to be able to set a bit on types so that any CData objects returned or manipulated by function calls had this bit set automatically.

   let libc = ctypes.open("libc.so.6");

   let malloc = libc.declare("malloc", ctypes.default_abi, ctypes.voidptr_t, ctypes.size_t);
   let ptr = malloc(2048);
   ptr = ptr.autofree(); // ptr is memory managed

   let malloc_af = libc.declare("malloc", ctypes.default_abi, ctypes.voidptr_t.autofree(), ctypes.size_t);
   let ptr = malloc_af(2048); // ptr is memory managed

   // This may not be feasible:
   let create_thing = library.declare("create_thing", ctypes.default_abi, ctypes.void_t, ctypes.voidptr_t.autofree().ptr());
   let thing = ctypes.voidptr_t();
   create_thing(thing.address()); // thing is most likely not memory managed, but it would be nice if it were.
Bug 720771 should address this need.

I initially wanted to do it using types, something like what you propose here, but taras suggested something that is less integrated with CTypes and I think it's better.
By the way - you should rarely need to call malloc or free from ctypes, because CTypes are JS constructors. So you can write:

    let buffer_t = ctypes.uint8_t.array();
    let buf = new buffer_t(2048);   // new array of 2048 bytes
    let ptr = buf.address();

The buffer is automatically freed when buf is collected.

Or if you just need enough memory for a particular struct, you don't even have to specify the size:

    let mystruct_t = ctypes.StructType(......);
    let buf = new mystruct_t;
    let ptr = buf.address();
Severity: normal → S3
You need to log in before you can comment on or make changes to this bug.