q66/cffi-lua

Segmentation fault when assigning a Lua callback to a C struct

Closed this issue · 2 comments

niess commented

Hello,

thank you for this great work :)

I am trying to adapt an existing LuaJIT+ffi project such that it could run with Lua as well using the cffi package. Doing so I am stuck with the following use case. When assigning a Lua callback to a C struct I get a segfault. Yet it works with LuaJIT. Below is a minimal example:

local ffi = jit and require('ffi') or require('cffi')

ffi.cdef([[
struct structure {
        void (*callback)(void);
};
]])

local structure = ffi.new('struct structure')
structure.callback = function () end

The last line gives a segfault on Debian using Lua 5.4+cffi. What could be the reason?

q66 commented

okay, that's fixed now, but generally don't do this; you have no way to :free() the callback afterwards, so you leak resources, and with luajit it's especially bad considering the callback limits

you should always cast the lua function first, then save the result, pass it where you want it, and explicitly :free() the callback once you're done with it

niess commented

Thanks!

I missed this point indeed. Usually my application uses only a few callbacks. Yet it could be problematic indeed. I will change this and make sure to :free().