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

Marco De Oliveira deolivem at gmail.com
Sat Feb 6 18:04:06 EST 2010


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)

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).
But with, i have still the behavior when I try this code in ghci.

Please, can you test this code and tell me why ghci stay blocked after
executing the method test.

BR

Marco

2010/2/6 Maciej Piechotka <uzytkownik2 at gmail.com>

> On Sat, 2010-02-06 at 12:28 +0100, Marco De Oliveira wrote:
> > Hi,
> >
> > I try to initialize a C struct using the FFI API and ghc stays blocked
> > when I execute my code (and I got sometimes the error "out of
> > memory").
> > I do not understand, I do not find any mistake in my code:
> >
> > {-# OPTIONS -XTypeSynonymInstances #-}
> >
> > import Foreign.C.Types
> > import Foreign.Marshal.Alloc
> > import Foreign.Ptr
> > import Foreign.Storable
> >
>
> It can be written as:
> import Foreign
> import Foreign.C
>
> >
> > type CStruct = (CULong, CULong)
> >
>
> I guess that you may want to use newtype or data rather then type to
> avoid clashes (and have just 98 + FFI):
>
> newtype CStruct = CStruct (CULong, CULong)
> data CStruct = CStruct CULong CULong
>
> > instance Storable CStruct where
> >   sizeOf _ = 2*sizeOf (undefined::CULong)
> >   alignment _ = alignment (undefined::CULong)
> >
>
> To begin with - where's peek and poke?
>
> > test = alloca (\pStruct -> do
> >          poke pStruct ( (fromIntegral 1)::CULong, (fromIntegral
> > 1)::CULong )
> >          )
>
> If you just do this at the beginning you may want to use with (notation
> as with newtype/data):
>
> with (CStruct (1, 1)) (\ptr -> ...)
>
>
> Also is main = test?
> > Thanks for your help.
> >
> > Marco
>
> Regards
>
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20100206/03455403/attachment.html


More information about the Beginners mailing list