RWH ch 17PI
に続いて、C値をHaskellのシンボルにバインドする何かを導入する必要があります。
例えば:
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE CPP #-}
import Foreign
import Foreign.C
-- helpers
import Control.Applicative
import Control.Monad
#include "foo.h"
-- binding a symbol
-- Note that hsc2hs can't marshal floating point CPP values, so this will be "3"
-- c_pi :: CInt
-- c_pi = #const PI
-- Instead, bind to a function that returns a CFloat
pi' :: Float
pi' = realToFrac c_pi
foreign import ccall unsafe "my_pi" c_pi :: CFloat
そして、私たちがここにいる間、Haskellとの間で構造体をマーシャリングすることもできます:
-- Marshalling for the struct foo
data Foo = Foo { i1, i2 :: Int }
deriving Show
-- Define how to marshal foo structs
instance Storable Foo where
sizeOf _ = #{size foo}
alignment _ = alignment (undefined :: CInt)
poke p foo = do
#{poke foo, i1} p $ i1 foo
#{poke foo, i2} p $ i2 foo
peek p = return Foo
`ap` (#{peek foo, i1} p)
`ap` (#{peek foo, i2} p)
そして関数にバインドしfooFkt
ます:
-- Import the function too
foreign import ccall "foo.h fooFkt"
c_fooFkt :: Ptr Foo -> IO CInt
-- Marshal data to and from C
fooFkt :: Foo -> IO Int
fooFkt f = fromIntegral <$> with f c_fooFkt
終わり。