Previous: create-signal-handler-closure, Up: Closures


8.2 Object-bound foreign functions

A common idiom for Gtk+ for passing user-defined function is as follows. Callback function has (besides its 'useful' arguments) an additional argument at the end - the 'data' pointer. This 'data' pointer, along with the pointer to 'destroy-notify' function is specified when passing the function. Destroy-notify function allows to free the function object (the Lisp closure) when it is not used by an object.

— Macro: define-cb-methods
     (define-cb-methods name return-type ((arg-1 type-1) ... (arg-n type-n)))

Defines two CFFI callbacks assosiated with the callback function type name. Creates name-cb - a callback to be passed as an function and create name-destroy-notify - a callback to be passed as 'destroy-notify' function. These callbacks are intended to work together with create-fn-ref.

Arguments and return-type are the same as CFFI arguments and return-type for callbacks. Arguments do not include the last 'data' pointer.

— Function: create-fn-ref
     (create-fn-ref object function) => foreign-pointer

This function creates a foreign structure containing the data neccesary for callbacks defined by define-cb-methods to call and dispose of the function. The function is bound to the object. This is neccesary for correct work of garbage collector. The created structure is freed by 'destroy-notify' function.

Example:

     (defcfun gtk-assistant-set-forward-page-func :void
       (assistant (g-object assistant))
       (page-func :pointer)
       (data :pointer)
       (destroy-notify :pointer))
     
     (define-cb-methods assistant-page-func :int ((current-page :int)))
     
     (defun set-assistant-forward-page-function (assistant function)
       (if function
           (gtk-assistant-set-forward-page-func assistant
                                                (callback assistant-page-func-cb)
                                                (create-fn-ref assistant function)
                                                (callback assistant-page-func-destroy-notify))
           (gtk-assistant-set-forward-page-func assistant (null-pointer) (null-pointer) (null-pointer))))