[plt-scheme] scheme/foreign, callbacks and NULL

From: Matthew Flatt (mflatt at cs.utah.edu)
Date: Thu Jan 1 16:49:45 EST 2009

At Thu, 01 Jan 2009 15:08:26 +0100, Andreas Rottmann wrote:
> Hi!
> 
> Writing an FFI compatiblity layer that targets Ikarus, PLT and Ypsilon,
> I have run into this problem on PLT: I want to bind a C function that
> takes a callback (function pointer) argument, and want to be able to
> pass a NULL pointer as callback. Here's some example code, using GLib:
> 
> #lang scheme
> 
> (require scheme/foreign
>          (only-in '#%foreign ffi-callback))
> 
> (unsafe!)
> 
> (define libglib (ffi-lib "libglib-2.0" '("0")))
> (define g-idle-add-full% (get-ffi-obj "g_idle_add_full" libglib _fpointer))
> 
> (define g-idle-add-full
>   (function-ptr g-idle-add-full%
>                 (_cprocedure (list _int _fpointer _pointer _fpointer) _uint)))
> 
> (define my-idle-callback
>   (ffi-callback (lambda args
>                   (printf "idle, args: ~s~n" args)
>                   1)
>                 (list _pointer)
>                 _int))
> 
> (g-idle-add-full 200 my-idle-callback #f #f)
> ;; EOF
> 
> This causes the following error when run:
> Scheme->C: expects argument of type <cpointer>; given #f

You can use `_pointer' instead of `_fpointer' as the last argument to
`g-idle-add-full%'.

I'll fix the docs to clarify that `_fpointer' doesn't allow NULL
pointers. Or maybe it should allow NULLs?


> PS: I know one is not really supposed to use `ffi-callback' directly,
>     but I need it to provide a compatible API across all
>     implementations.

Another doc issue: I forgot to update the docs for `function-ptr' to
say that you can provide a Scheme procedure as the first argument. So,
you could use `function-ptr' instead of `ffi-callback'.


Matthew



Posted on the users mailing list.