0

Read in Python CFFI documentation:

The interface is based on LuaJIT’s FFI (...)

Read on LuaJIT website (about ffi.gc()):

This function allows safe integration of unmanaged resources into the automatic memory management of the LuaJIT garbage collector. Typical usage:

local p = ffi.gc(ffi.C.malloc(n), ffi.C.free)
...
p = nil -- Last reference to p is gone.
-- GC will eventually run finalizer: ffi.C.free(p)

So, using Python-CFFI, do you have to trigger the destruction of the last reference to a variable instantiated using ffi.gc (= that needs a special function for deallocation because some parts of it are dynamically allocated) by setting it to (i.e.) ffi.NULL ?

Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85
DRz
  • 1,078
  • 1
  • 11
  • 29
  • Does "Unlike C, the returned pointer object has ownership on the allocated memory: when this exact object is garbage-collected, then the memory is freed." answer your question? From http://cffi.readthedocs.org/en/latest/using.html – Etan Reisner Mar 31 '16 at 20:14
  • Your quote only works for objects allocated on the stack, using ffi.new (and ffi.cast?), doesn't it? – DRz Mar 31 '16 at 20:21
  • No idea. But it looks like it works the same (from the same page: "ffi.gc(cdata, destructor): return a new cdata object that points to the same data. Later, when this new cdata object is garbage-collected, destructor(old_cdata_object) will be called. Example of usage: ptr = ffi.gc(lib.malloc(42), lib.free). Note that like objects returned by ffi.new(), the returned pointer objects have ownership, which means the destructor is called as soon as this exact returned object is garbage-collected.") – Etan Reisner Mar 31 '16 at 20:35

1 Answers1

1

Python is designed so that all objects are garbage collected as soon as there is no more reference to it (or soon afterwards), like any other garbage-collected language (including Lua). The trick of setting p = None explicitly (or del p) will merely make sure that this local variable p does not keep the object alive. It is pointless (barring special cases) if, for example, it is one of the last thing done in this function. You don't need it any more than you need it to free, say, a variable that would contain a regular string object.

Armin Rigo
  • 12,048
  • 37
  • 48