Using the Haskell FFI to marshal structs; also, how to use FunPtr
I have some questions about the ffi in haskell
.
first of all i'm trying to work with c st开发者_Go百科ructs in haskell
.
there i have some questions: i have a struct like
struct foo{int a; float b;};
- when could i use
data Foo = Foo { a :: Int, b :: Float } deriving (Show, Eq)
- when i have to implement a storable with peek and poke?
okay now a question about FunPtr
- i dont know when to use
FunPtr
why a normal definition likePtr CInt -> IO CInt
is not enough?
Marshalling
To marshal structures, you will need to use a Storable
class instance to marshal data back and forth, via peek
and poke
.
See this previous answer for an example: How to use hsc2hs to bind to constants, functions and data structures?
FunPtr
FunPtr
is only needed when you want to pass a function across the FFI boundary as a first-class value, not for calling foreign functions. Precisely:
A value of type FunPtr a is a pointer to a function callable from foreign code. The type a will normally be a foreign type, a function type with zero or more arguments
An example, registering a call back function:
foreign import ccall "stdlib.h &free"
p_free :: FunPtr (Ptr a -> IO ())
Since we have to pass p_free
itself to a Haskell function, we have to let Haskell know this is actually a C function. The FunPtr
wrapper controls that.
精彩评论