FFI in Haskell, question about the LANGUAGE CPP and how to use a c struct with the FFI
I have some questions about the FFI in Haskell
- I know i must use the language pragma
{-# LANGUAGE ForeignFunctionInterface #-}
but what is the difference when i use{-# LANGUAGE CPP, ForeignFunctionInterface #-}
what can i do "more" with the CPP - i use a function in c which use a
struct
, how c开发者_如何学编程an i handle this in the FFI? - when i have to use
CInt
and when justInt
?
- If you enable the
CPP
language extension, you can then legally encorporate C pre-processor syntax into your Haskell program. - To access a struct is a little more complicated. The easiest way is probably to use the
Storable
typeclass to definepeek
andpoke
methods for each field of the struct. The hsc2hs tool can help. - You use
CInt
whenever you need to pass a HaskellInt
to or from C, as this will ensure any required marshalling takes place (same goes forCDouble
,CString
and so on).
The X11 package has many examples of defining and marshalling structs via the FFI.
More info in:
- RWH ch 17.
- FFI Introduction on the Haskell wiki
- Foreign.* in the base library
CPP
is the C preprocessor. It allows you to use conditional compilation and makros. Usually, you don't need this, but it becomes useful, as soon as you have platform-dependent code, where the code to compile is decided by an external script (like with the autotools).- Have a look at c2hs
- Use
Cint
only for the direct import. When writing a high-level binding, switch toInt
as it doesn't requires the user to import the required libraries and is Haskell standard
精彩评论