[Haskell-beginners] Re: Re: How to initialize a C struct with FFI

Maciej Piechotka uzytkownik2 at gmail.com
Sat Feb 6 18:44:38 EST 2010

On Sun, 2010-02-07 at 00:04 +0100, Marco De Oliveira wrote:
> Hi Maciej,
> Thanks to have take some time to read this code.
> I rewrite using your comments:
> import Foreign
> import Foreign.C
> data CStruct = CStruct (CULong, CULong)

Hmm. You combined both newtype and data. While technically it is correct
you have now one level more for program to consider. 

> instance Storable CStruct where
>   sizeOf _ = 2*sizeOf (undefined::CULong)
>   alignment _ = alignment (undefined::CULong)
> test = with (CStruct (1,1)) (\ptr -> return ())
> The class Storable does not need to make your own peek and poke method
> (the class provide a default implementation).

Not quite. It does in terms of peek/pokeElemOff. Which has in terms of
peek/pokeByteOff which has implementation in terms of peek/poke itself.

Therefore you have infinite recursion - poke calls pokeElemOff which
calls pokeByteOff which calls poke etc. 

Even the documentation specifies this:
"Minimal complete definition: sizeOf, alignment, one of peek,
peekElemOff and peekByteOff, and one of poke, pokeElemOff and

Sorry - I forgot about this (I only noticed that something is missing).

> But with, i have still the behavior when I try this code in ghci.

My other suggestions only caused to avoid extensions/have type safety
and shorten the function respectively - they did not alter behaviour.



More information about the Beginners mailing list