Next Prev Up Top Contents Index

2.4.2 An example

For example, let us assume that we want to pass Lisp object handles through to C and then back to Lisp again. Passing C a pointer to the Lisp object is not sufficient, as the Lisp object might be moved at any time, for example due to garbage collection. Instead, we could assign each Lisp object to be passed to C a unique int handle. Callbacks into Lisp could then convert the handle back into the Lisp object. This example is implemented in two ways: using the :wrapper type and using fli:define-foreign-converter

:wrapper

Type

Allows the specification of automatic conversion functions between Lisp and an instance of an FLI type.

:wrapper fli-type &key lisp-to-foreign foreign-to-lisp

Using :wrapper we can wrap Lisp to C and C to Lisp converters around the converters of an existing type:

(fli:define-foreign-type lisp-object-wrapper ()
  "A mechanism for passing a Lisp object handle to C.
   Underlying C type is Lint"
 `(:wrapper :int
   :lisp-to-foreign find-index-for-object
   :foreign-to-lisp find-object-from-index))

If the :lisp-to-foreign and :foreign-to-lisp keyword arguments are not specified, no extra conversion is applied to the underlying foreign type, causing it to behave like a standard :int type.

See the reference entry for :wrapper for more examples.

define-foreign-converter

Function

Defines a new converter type for converting from Lisp to C and C to Lisp.

define-foreign-converter fli-type object &key lisp-to-foreign foreign-to-lisp

A second method uses fli:define-foreign-converter , which is specifically designed for the creation of new converter types (that is, types which wrap extra levels of conversion around existing types). A simple use of define-foreign-converter is to only wrap extra levels of conversion around existing Lisp to foreign and foreign to Lisp converters.

(fli:define-foreign-converter lisp-object-wrapper () object
  :foreign-type :int
  :lisp-to-foreign `(find-index-for-object ,object)
;; object will be the Lisp Object
  :foreign-to-lisp `(find-object-from-index ,object)
;; object will be the :int object
  :documentation "Foreign type for converting from lisp objects to
integers handles to lisp objects which can then be manipulated in
C. Underlying foreign type : 'C' int")

The definition of lisp-object-wrapper using define-foreign-converter is very similar to the definition using :wrapper , and indeed the :wrapper type could be defined using define-foreign-converter .


LispWorks Foreign Language Interface User Guide and Reference Manual - 14 Dec 2001

Next Prev Up Top Contents Index