Re: FFI - coroutine.yield/resume inside callback

  • From: Michal Kottman <k0mpjut0r@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Fri, 25 May 2012 09:59:49 +0200

On 24 May 2012 10:01, Richard Hundt <richardhundt@xxxxxxxxx> wrote:
> Just a heads up, it works beautifully :)
>
> However, this is what bit me: you can't keep a reference to a member of the 
> object returned via ffi.load after the object itself has been garbage 
> collected.
>
> function loadlib()
>   local mylib = assert(ffi.load('mylib')) -- mylib gets GC'ed eventually
>   return { some_function = mylib.mylib_some_function }
> end
>
> local l = loadlib()
> l.some_function() -- sooner or later doing this is going to blow up when 
> mylib above gets collected

I've been hit by this more than once (forgetting to save a reference).
Basically I have a Lua C function which returns a userdata filled by
some data, which I later ffi.cast() to a more appropriate type in Lua.
The problem was that I never saved the reference to the userdata,
which was then garbage collected.

The main point to remember: save a reference along with the casted data.

local points = mylib.calculatePoints()
return {
  points_ptr = points, -- keep a reference so it is not garbage collected
  points = ffi.cast('Point*', points)
}

Your case is a similar issue to this one.

Other related posts: