繼RWH ch 17,您需要引入一些將C PI
值綁定到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
雖然我們在這裏,我們也可以在封結構,並從哈斯克爾:
-- 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
完成。
不綁定 - dsl提供了一些float常量#defines? #分數或類似的東西? – aleator 2011-05-19 19:16:07
綁定-DSL爲您提供了一些其他非常有用的東西。我強烈建議:https://bitbucket.org/mauricio/bindings-dsl/wiki/DetailedUsageGuide – sclv 2011-05-19 19:41:42