开发者

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

  1. 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
  2. i use a function in c which use a struct, how c开发者_如何学编程an i handle this in the FFI?
  3. when i have to use CInt and when just Int?


  1. If you enable the CPP language extension, you can then legally encorporate C pre-processor syntax into your Haskell program.
  2. To access a struct is a little more complicated. The easiest way is probably to use the Storable typeclass to define peek and poke methods for each field of the struct. The hsc2hs tool can help.
  3. You use CInt whenever you need to pass a Haskell Int to or from C, as this will ensure any required marshalling takes place (same goes for CDouble, 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


  1. 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).
  2. Have a look at c2hs
  3. Use Cint only for the direct import. When writing a high-level binding, switch to Int as it doesn't requires the user to import the required libraries and is Haskell standard
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜