Re: ffi.cast to "type *" for C callbacks causes crash if used many times

  • From: Mike Pall <mike-1208@xxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Sun, 12 Aug 2012 01:30:56 +0200

Adrian Smith wrote:
> I have found that ffi.cast(“<type> *”, func) rather than
> ffi.cast(“<type>”, func) for C callbacks can cause segfaults after
> multiple calls.  Even if the resulting type is always the same it
> appears to create calls to ctype_new() and additional allocation of
> type ids within luajit which eventually causes a segfault after a C
> callback is processed.

I fixed the segfault in git HEAD. Thank you for the report!

Creation of a new pointer type every time is hard to avoid, due to
the internal semantics of C function types.

> The actual library is Spotify's libspotify which
> defines its callback typedef as function types not pointers to
> functions, so its natural to do the cast to "<type> *" using the
> typedefs defined by the library (as per the problem example).

A function typedef is rarely a good idea in C. I suggest to define
your own function *pointer* typedef (once!), to avoid the above

> I'm not sure if cb:free() should be called within the callback
> itself, but it seems to work - is this advised?

This works fine.


Other related posts: