[Cffi-devel] Callbacks & Lambdas

Joerg-Cyril.Hoehle at t-systems.com Joerg-Cyril.Hoehle at t-systems.com
Mon Nov 10 20:01:55 UTC 2014


On Wed, Nov 5, 2014 at 7:53 AM, FAU <fau at riseup.net> wrote:
> Is there a reliable/portable way to have lambdas called as a callback 
> from a foreign C function?  I assume there's not though.

The CLISP FFI has had lambda callbacks since FFI day 1, 20 years ago, as well as other implementations.

The issue with callbacks in CFFI is IMHO one of proper resource deallocation. No one AFAIK has devised a KISS-style lambda callback creation *AND DEALLOCATION* protocol. The reason why deallocation is important is that every lambda callback needs dynamic creation of what the CLISP libffi and GCC call a trampoline. The Lisp system cannot itself determine when the callback trampoline is not needed anymore, so the application MUST tell it.

Various Lisp implementation have baroque restrictions on the number of callbacks (I seem to remember numbers as low as 255 for one). Lambda callback makes it trivial to inadvertently create unnumbered callbacks (e.g. reload your Lisp source during development, run some function in a loop...) as opposed to unique named functions, so the risk of leaking memory is high. The lambda callback APIs in existing Lisp implementations differ a lot. These observations combined make an attempt at portable lambda callbacks a hairy job.

>I know one of the GTK bindings did something like this, but it used some GTK-specific tricks.
Can't remember about GTK, I may have LTK in memory, and the simple trick was that lambda was not actually needed. There was a single callback function from the foreign POV, so a unique named function could be used. That Lisp function then did some work to identify the actual Lisp callback and supply it with useful arguments.

Regards,
	Jörg Höhle


More information about the cffi-devel mailing list