modeling ANSI C structs in Haskell?

Hello, 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? Vasili

Vasili, On 04/02/2008, at 10:04 PM, 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?
The FFI spec is a wonderful document, but is of limited use in learning to use the FFI for practical tasks. I suggest you look into c2hs or some other tool that tries to help you with marshalling data structures (as compared to providing mechanisms sufficient for doing marshalling). I suggest you do this even if you don't end up using a tool, as the generated Haskell has some carefully designed idioms that will definitely help. cheers peter

On 2/4/08, Galchin Vasili
Hello,
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?
Maybe this could offer some help http://therning.org/magnus/archives/315 /M

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). HTH Ben
participants (4)
-
Ben Franksen
-
Galchin Vasili
-
Magnus Therning
-
Peter Gammie