q66 / cffi-lua

A portable C FFI for Lua 5.1+
MIT License
176 stars 24 forks source link

Segmentation fault when assigning a Lua callback to a C struct #25

Closed niess closed 3 years ago

niess commented 3 years ago

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 3 years ago

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 3 years ago

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().