Galchin, Vasili wrote:
Hello,

       I want to model a Haskell function that is a callback from C. I have
only found one example in the unix package's Semaphore.hsc, which apparently
is not used. I want to be able to marshall a Haskell function that is a
first class citizen residing in a Haskell data type and pass to a C function
via FFI. Are there examples of this?

Attached is a simple example.

The main thing to note is 'foreign import ccall "wrapper"' which gives you a factory for turning Haskell functions into foreign function pointers.

More information:

http://www.cse.unsw.edu.au/~chak/haskell/ffi/


Claude
--
http://claudiusmaximus.goto10.org

module Main(main) where

import Foreign.C.Types(CDouble)
import Foreign.Ptr(FunPtr, freeHaskellFunPtr)

foreign import ccall "wrapper"
  wrap :: (CDouble -> CDouble) -> IO (FunPtr (CDouble -> CDouble))

foreign import ccall "callerback.h twice"
  twice :: FunPtr (CDouble -> CDouble) -> CDouble -> IO CDouble

square :: CDouble -> CDouble
square x = x * x

main :: IO ()
main = do
  squareW <- wrap square
  let x = 4
  y <- twice squareW x
  z <- twice squareW y
  print y
  print z
  freeHaskellFunPtr squareW
#include "callerback.h"

double twice(d2d f, double x) {
  return f(f(x));
}

#ifndef CALLERBACK_H
#define CALLERBACK_H
typedef double (d2d)(double);
double twice(d2d f, double x);
#endif
CallBacker: CallBacker.hs callerback.c callerback.h
        ghc -O2 -Wall -fffi -o CallBacker CallBacker.hs callerback.c
_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to