Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FFI in Haskell, question about the LANGUAGE CPP and how to use a c struct with the FFI

Tags:

haskell

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 can i handle this in the FFI?
  3. when i have to use CInt and when just Int?
like image 749
ewggwegw Avatar asked May 04 '11 19:05

ewggwegw


2 Answers

  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
like image 144
Don Stewart Avatar answered Nov 16 '22 05:11

Don Stewart


  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
like image 39
fuz Avatar answered Nov 16 '22 07:11

fuz