need help with ffi function pointers
wolfgang.thaller at gmx.net
Sun Mar 2 05:24:07 EST 2003
> I'm working on interfacing a c library that has the
> notion of callbacks.
> I have a C function:
> f_setCallback( void (funptr*) () );
> I would like to allow a haskell developer to have an
> interface like the following:
> callback :: IO ()
> callback = putStr "Called!\n"
> main :: IO ()
> main = do
> setCallback callback
> -- etc.
> Is this possible via. ffi? If so, how would I do it
> code wise?
foreign import ccall "wrapper" mkCallback :: IO () -> FunPtr (IO ())
foreign import ccall "f_setCallback" f_setCallback :: FunPtr (IO ()) ->
setCallback cb = mkCallback cb >>= f_setCallback
That solution has one slight disadvantage, though:
mkCallback dynamically creates an "adjustor thunk", which is a short
piece of machine code that translates from the C calling convention to
Haskell. This thunk should be freed using freeHaskellFunPtr when it is
no longer needed (i.e. when a different callback is installed). So
setCallback should really check if there is already a _Haskell_
callback installed, and if so, free it using freeHaskellFunPtr.
Otherwise, you'd have a small memory leak.
More information about the FFI