Re: Making FFI callbacks call free() automatically when it's collected

  • From: Mike Pall <mike-1207@xxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Thu, 19 Jul 2012 11:20:10 +0200

Johnson Lin wrote:
> Since anonymous FFI callbacks are anchored permanently, and explicitly
> call cb:free() every time is pretty troublesome too, is it considered
> good to do this?
> local cb = ffi.gc(ffi.cast("CALLBACK", function() end), function(self)
> self:free() end)
> cb()
> cb = nil
> collectgarbage("collect")
> I did print some messages in the callback body and the finalizer body
> to verify it's working.

This works. But the time when the GC gets around to collect the
callback slot is not predictable. Since the slots are a scarce
resource, you may run out of them.

You need know the exact point in time when the callback is no
longer used, anyway. IMHO it's better to create a convenience

local function wrap_iter(func)
  local cb = ffi.cast("CALLBACK", func)

wrap_iter(function() end)


Other related posts: