Skip to content

Instantly share code, notes, and snippets.

@wavewave
Created September 1, 2013 15:10
Show Gist options
  • Save wavewave/6405018 to your computer and use it in GitHub Desktop.
Save wavewave/6405018 to your computer and use it in GitHub Desktop.
haskell callback with captured variable
module Main where
import Foreign.C.Types
import Foreign.Ptr
foreign import ccall "wrapper"
wrap :: (CDouble -> CDouble) -> IO (FunPtr (CDouble -> CDouble))
foreign import ccall "callerback.h twice"
twice :: FunPtr (CDouble -> CDouble) -> CDouble -> IO CDouble
myfunc :: CDouble -> CDouble -> CDouble
myfunc y x = y * (x * x)
main :: IO ()
main = do
myfuncW <- wrap (myfunc 2)
let x = 4
y <- twice myfuncW x
z <- twice myfuncW y
print y
print z
freeHaskellFunPtr myfuncW
#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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment