Re: metatype __gc inconsistency

  • From: Mike Pall <mike-1409@xxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Thu, 18 Sep 2014 17:29:04 +0200

Tomash Brechko wrote:
>   ffi = require("ffi")
>   ffi.cdef[[ struct S {}; struct S *malloc(size_t size); ]]
>   ffi.metatype("struct S", {
>      __len = function() return 5 end,
>      __gc = function() print("GC") end
>   })
>   s1 = ffi.new("struct S")

This returns a struct.

>   s2 = ffi.C.malloc(1)

This returns a pointer to a struct.

>   collectgarbage()
>   s1 = nil
>   collectgarbage() -- Outputs "GC" - good
>   s2 = nil
>   collectgarbage() --  Output nothing - why?

Well, why should it do anything? The pointer cdata object is
collected, not the struct it points to.

> Not claming that it's a bug, my guess this is intentional and one has to do
> ffi.gc(s2, ...), but why?  What is the rationale for not calling metatype
> __gc when object is allocated outside of LuaJIT?

Because memory allocated outside of LuaJIT is (obviously) not
under control of the GC.

The pointer cdata object is under control of the GC, but it can't
just go out of it's way and call __gc for the corresponding struct
if any pointer object is collected. You could have many pointers
to the same struct. The GC doesn't track external memory, unless
you explicitly tell it to do so via an anchor pointer object.

--Mike

Other related posts: