lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


* Mike Pall:

> Florian Weimer wrote:
>> * Mike Pall:
>> > tl;dr: Just pass a Lua function to a C function taking a callback
>> > argument and the FFI will do all the magic in the background.
>> 
>> I'm trying to figure out what made this feat suddenly possible.
>
> Magic, of course. And careful planning.
>
>> I was under the impression that it wouldn't be possible introduce,
>> say, allocations into traces which were deemed allocation-free
>> before.
>
> Umm? 1) Why not? 2) I do not see any relation to callbacks.

Let me phrase this a bit differently.  I think you need to fake a side
exit if a callback into Lua happens while a compiled trace is running
because the preconditions for that trace are no longer necessarily
valid.

The following segfaults for me without -joff using git HEAD.
(I somewhat expected it would print "0".)

local ffi = require("ffi")
ffi.cdef [[
void set_callback(void (*)(void));
void perform(void);
]]
local lib = ffi.load("./callback.so")

local counter = 0
local doit
local cb
do
   local increment = 0
   local function f()
      increment = 1
   end
   cb = ffi.cast("void(*)(void)", f)
   lib.set_callback(cb)
   function doit()
      counter = counter + increment
   end
end

for i = 1, 2000 do
   lib.perform()
   doit()
end
print(counter)

/* Compile with: gcc -Wall -W -O2 -shared -g -o callback.so callback.c */

static void (*cb)(void);
static unsigned counter;

void
set_callback(void (*f)(void))
{
  cb = f;
  counter = 0;
}

void
perform(void)
{
  ++counter;
  if (counter == 1000) {
    cb();
  }
}