[racket] FFI callback object pointer

From: Thomas Chust (chust at web.de)
Date: Sat Jul 17 09:18:44 EDT 2010

2010/7/17 gabor papp <gabor.lists at mndl.hu>:
> [...]
> What I'm trying to do is passing a boxed variable to the FFI module, and
> when the C library changes the variable it calls the set callback, in which
> I set the content of the box.
>
> I would like to pass the box through the client-data pointer, so the
> callback can do this, but I'm not sure how to do it. Is it possible to
> achieve something like this with FFI?
> [...]

Hello Gabor,

nearly everything is possible ;-)

I think you should consider encapsulating the type of values that can
be passed around and the box to store them in the closure of the
getter and setter callbacks, which may be much more convenient than
creating a C data structure that can hold this information.

Example code follows:

-----BEGIN "callmeback.c"-----
typedef void (* Accessor)(void *loc);

int call_int_getter(Accessor getter) {
  int val;
  getter(&val);

  return val;
}

void call_int_setter(Accessor setter) {
  int val = 42;
  setter(&val);
}
-----END "callmeback.c"-----

-----BEGIN "callmeback.rkt"-----
#lang racket
(require ffi/unsafe)

;;; Interface to C library

(define libcallmeback
  (ffi-lib "libcallmeback"))

(define _accessor
  (_fun (val : _pointer) -> _void))

(define call-int-getter
  (get-ffi-obj
   "call_int_getter" libcallmeback
   (_fun (getter : _accessor) -> _int)))

(define call-int-setter
  (get-ffi-obj
   "call_int_setter" libcallmeback
   (_fun (setter : _accessor) -> _void)))

;;; Accessor generator

(define (make-int-accessors val)
  (values
   ;; getter
   (λ (loc)
     (ptr-set! loc _int val))
   ;; setter
   (λ (loc)
     (set! val (ptr-ref loc _int)))))

;;; A simple test

(define-values (my-getter my-setter)
  (make-int-accessors 23))

(display (call-int-getter my-getter))
(newline)

(call-int-setter my-setter)

(display (call-int-getter my-getter))
(newline)
-----END "callmeback.rkt"-----

Accessors for other types than int can trivially be implemented along
the same lines.

Ciao,
Thomas


-- 
When C++ is your hammer, every problem looks like your thumb.


Posted on the users mailing list.