FWIW here's the awful hack I'm using for now: Lua: local util = require "util" function magic(f) local bf = util.make_function_box() ffi.cast("void **", bf)[0] = f return util.unbox_function_box(bf) end f = C.factory() -- factory is an FFI-bound function which returns a lua_CFunction g = magic(f) g() -- works util is a Lua module in C, with these functions: static int make_function_box(lua_State * L) { lua_newuserdata(L, sizeof(lua_CFunction *)); return 1; } static int unbox_function_box(lua_State * L) { lua_CFunction * f = (lua_CFunction *)lua_touserdata(L, 1); lua_pushcclosure(L, *f, 0); return 1; } On May 13, 2012, at 2:37 PM, GrrrWaaa wrote: > > I am binding an API which includes a factory function that furnishes valid > lua_CFunction pointers. I want to be able to call this factory via the FFI, > and use its return values directly as if they were Lua functions: > > ffi.cdef[[ > lua_CFunction factory(); > ]] > local f = C.factory() > local g = <some magic with f> > g() > > I can't figure out what magic is needed to convert a <cdata> into a function, > and would welcome any suggestions from the brilliant minds on this list. > > I tried writing a small helper C library, but of course cdata don't interact > with the C API stack functions. > > Also tried calling lua_pushcclosure using the FFI, but it doesn't seem to > work either: > > ffi.cdef[[ > lua_CFunction factory(); > > typedef struct lua_State lua_State; > typedef int (*lua_CFunction) (lua_State *L); > void (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n); > ]] > > local f = C.factory() > > local L = <a C library function to call lua_pushlightuserdata(L, L); > > local g = C.lua_pushcclosure(L, f, 0) > print("g", g) --> nil > > Is this because in the FFI we can't manipulate a coroutine stack while it is > running?