[plt-scheme] Question About FFI Callbacks

From: Will Farr (farr at MIT.EDU)
Date: Tue Aug 26 09:55:39 EDT 2008

Hello all,

I have a quick question about FFI Callbacks.  I'm trying to wrap up  
some more of the GSL (the parts involving integration and numerical  
differentiation) which require the user to supply a procedure that  
implements the function to be integrated or differentiated.  This  
requires callbacks.  These functions want to get a pointer to a C  
struct defined as

struct gsl_function_struct
{
   double (* function) (double x, void * params);
   void * params;
};

typedef struct gsl_function_struct gsl_function ;

This is a manually-created closure (which I won't need because the FFI  
will take care of closing over local scope when it creates a callback,  
but is still a nice gesture on the part of the GSL designers).  I  
would like to wrap it up in a cstruct object in the FFI as follows:

(define-cstruct _gsl-function
   ((function (_fun _double _pointer -> _double))
    (params _pointer)))

But, when I do, trying to create a _gsl-function struct gives the  
following error:

(make-gsl-function (lambda (x junk) x) #f) => ptr-set!: setting  
fpointer value with extra arguments

Am I doing something wrong?  Is this an FFI bug?  Have I just missed  
the boat on callbacks, and the FFI is not as amazing as it sounds  
about automagically handling everything?  Thanks for any help you can  
give me.

Will

P.S.---This would also be a good time for somebody to recoil in horror  
about the possibility of memory-management issues (i.e. function  
pointers moving during callbacks and not getting corrected on the GSL  
stack, etc), if that's an issue.  Thanks again!


Posted on the users mailing list.