[cffi-devel] Re: Passing Lisp values into and back out of C?

James Bielman jamesjb at haytonsystems.com
Wed Mar 14 19:04:17 UTC 2007


On Wed, 2007-03-14 at 17:03 +0000, Luis Oliveira wrote:
> Peter Seibel <peter at gigamonkeys.com> writes:
> > Other than keeping my own integer->object mapping and passing the
> > integer to C and translating it back to the object when I get it back,
> > is there some easier way to do this in CFFI?
>
> Hmm, since you're asking whether this is doable in *CFFI*, the answer is
> no then. :-)  You can, however, make good use of CFFI's type system!

If the use case is passing Lisp data to callbacks limited to a certain
dynamic extent, you could do this easily by consing bindings from ints
to Lisp objects on an association list...  Something like:

;;; Counter used to generate unique IDs for Lisp objects passed to
;;; foreign code.  The counters are only guaranteed to be unique
;;; during the dynamic extent of which they are bound.
(defvar *lisp-object-counter* 0)

;;; Association list of Lisp object IDs to Lisp objects.
(defvar *lisp-objects* nil)

;;; Create a binding for a unique ID to a Lisp object during the
;;; extent of BODY.  The ID may be coerced to a pointer and passed to
;;; foreign code, then looked up from callback functions.
(defmacro with-lisp-object-id ((id object) &body body)
  `(let* ((,id *lisp-object-counter*)
          (*lisp-object-counter* (1+ *lisp-object-counter*))
          (*lisp-objects* (acons ,id ,object *lisp-objects*)))
     , at body))

Then you can pass the IDs as pointers to functions that take a callback 
and user data pointer, and ASSOC them in *LISP-OBJECTS* inside the
callback.

James





More information about the cffi-devel mailing list