Created
September 1, 2013 15:10
-
-
Save wavewave/6405018 to your computer and use it in GitHub Desktop.
haskell callback with captured variable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include "callerback.h" | |
| double twice(d2d f, double x) { | |
| return f(f (x)); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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