Created
May 11, 2011 07:19
-
-
Save ijt/966037 to your computer and use it in GitHub Desktop.
Example of calling C from Haskell using the FFI
This file contains 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
{-# LANGUAGE ForeignFunctionInterface #-} | |
-- Simple example of calling C from Haskell. | |
-- | |
-- $ ghci | |
-- > :load FfiExample.hs | |
-- > c_sin pi | |
-- 1.2246467991473532e-16 | |
-- | |
-- $ ghc --make FfiExample.hs | |
-- $ ./FfiExample | |
module Main where | |
import Foreign | |
import Foreign.C.Types | |
import Foreign.C.String | |
import Text.Printf | |
-- http://book.realworldhaskell.org/read/interfacing-with-c-the-ffi.html | |
foreign import ccall "math.h sin" | |
c_sin :: CDouble -> CDouble | |
foreign import ccall "stdlib.h system" | |
c_system :: CString -> IO CInt | |
sin2 :: Double -> Double | |
sin2 x = | |
realToFrac $ c_sin $ realToFrac x | |
system :: String -> IO CInt | |
system cmd = | |
withCString cmd c_system | |
main = do | |
putStrLn (printf "sin 3.14 = %.3f" (sin2 3.14)) | |
putStrLn "ls:" | |
system "ls" | |
return () |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment