Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a Storable instance for this type?

Suppose I have the following C structure:

typedef struct _Ready {
    int ready;
} *Ready;

I represent it in Haskell using this type:

data Ready = Ready { ready :: CInt }

Now I want a Storable instance. The following works fine:

instance Storable Ready where
    alignment = sizeOf
    sizeOf _  = (#size Ready)

However, adding any of these definitions of peek and poke fails:

    peek p = Ready <$> (#peek Ready, ready) p   -- FAILS
    poke p (Ready r) = (#poke Ready, ready) p r -- FAILS

The error boils down to ready not being part of a structure or union:

/usr/lib/ghc-7.10.1/template-hsc.h:72:24:
  error: request for member ‘ready’ in something not a structure or union

What am I doing wrong?

Thanks!

like image 964
liszt Avatar asked Feb 10 '26 22:02

liszt


1 Answers

Ready (the C type) is not a struct or a union, it's a pointer to a struct _Ready. You should use struct _Ready instead, like

peek p = Ready <$> (#peek struct _Ready, ready) p
poke p (Ready r) = (#poke struct _Ready, ready) p r

Also, your sizeOf method is wrong and needs the same change. You need the size of the struct, but you currently have the size of a pointer to the struct, and they are usually not the same on a 64-bit system.

like image 120
Reid Barton Avatar answered Feb 13 '26 19:02

Reid Barton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!