[Haskell-cafe] Re: modeling ANSI C structs in Haskell?

Ben Franksen ben.franksen at online.de
Thu Feb 7 20:07:43 EST 2008

Galchin Vasili wrote:
>       I am reading through the FFI doc. Any suggestions on enabling
>       Haskell
> programmers to model ANSI C structs that will be passed down to C
> run-time?

If you have a C function that needs to be passed a struct, then there are
three scenarios:

(a) A common situation is that your C struct is opaque (or at least meant to
be used opaquely). You'll have explicit allocate+construct functions as
well as deallocate+destruct functions in your C library. This means that
you don't care at all how to marshall the struct, you don't even (need to)
know how it looks like. All you work with is pointers (i.e. Ptr a, or Ptr X
where X is an empty data type). You can use ForeignPtr to automatically
call the Library provided destructor when the GC finds that the pointer is
no longer accessible in your program (from the Haskell side).

(b) In case the C function expects a pointer to a user allocated struct,
your type X will probably be a Haskell record, and you want to make X an
instance of class Storable. You can allocate and deallocate the C struct by
using one of the functions provided by Foreign.Marshal.Alloc.

(c) Most uncommon (though not not unheard of): the function gets the struct
passed by value. This means you can't write the FFI code completely in
Haskell because Haskell FFI can only work with C primitive types (numbers,
pointers, etc). You need to write a little C wrapper to convert
pass-by-value to pass-by-reference. Then see case (b).


More information about the Haskell-Cafe mailing list