Next: , Previous: , Up: Callbacks   [Contents][Index]


defcallback

defcallback

Syntax

Macro: defcallback name-and-options return-type arguments &body body ⇒ name

name-and-options ::= name | (name &key convention) arguments ::= ({ (arg-name arg-type) }*)

Arguments and Values

name

A symbol naming the callback created.

return-type

The foreign type for the callback’s return value.

arg-name

A symbol.

arg-type

A foreign type.

convention

One of :cdecl (default) or :stdcall.

Description

The defcallback macro defines a Lisp function that can be called from C. The arguments passed to this function will be converted to the appropriate Lisp representation and its return value will be converted to its C representation.

This Lisp function can be accessed by the callback macro or the get-callback function.

Portability note: defcallback will not work correctly on some Lisps if it’s not a top-level form.

Examples

  (defcfun "qsort" :void
    (base :pointer)
    (nmemb :int)
    (size :int)
    (fun-compar :pointer))
   
  (defcallback < :int ((a :pointer) (b :pointer))
    (let ((x (mem-ref a :int))
          (y (mem-ref b :int)))
      (cond ((> x y) 1)
            ((< x y) -1)
            (t 0))))
   
  CFFI> (with-foreign-object (array :int 10)
          ;; Initialize array.
          (loop for i from 0 and n in '(7 2 10 4 3 5 1 6 9 8)
                do (setf (mem-aref array :int i) n))
          ;; Sort it.
          (qsort array 10 (foreign-type-size :int) (callback <))
          ;; Return it as a list.
          (loop for i from 0 below 10
                collect (mem-aref array :int i)))(1 2 3 4 5 6 7 8 9 10)

See Also

callback
get-callback


Next: , Previous: , Up: Callbacks   [Contents][Index]