[Haskell-cafe] Writing a Storable instance for a C union
Nikita Karetnikov
nikita at karetnikov.org
Fri Dec 13 23:24:29 UTC 2013
> You can peek the "key", and then, depending on its value, return a
> different constructor :
> data MyStruct = MyStructOne Foo
> | MyStructFour Integer
> | MyStructTwenty [Blah]
OK, but how can I pick one of the union fields? Also, I’d rather change
MyStruct to Union in the above since I already defined MyStruct, which
has a Storable instance that looks like so (omitting sizeOf, alignment,
and poke):
instance Storable MyStruct where
peek p = do
v0 <- peekByteOff p 0
return $ MyStruct v0
This allows to get the value of key, and I could change it to get one of
the union fields:
instance Storable MyStruct where
peek p = do
v0 <- peekByteOff p 0
v1 <- peekByteOff p 4
return $ MyStruct v0 v1
But that would require to define a Storable instance for the Union type,
which is exactly the point of the thread. How can I do so? (Note that
Foo, Word64, and (Ptr a) are instances of Storable themselves.)
The other question that remains unanswered is how to make such code
portable. Should I rely on hsc2hs to determine things like sizeOf and
alignment?
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 835 bytes
Desc: not available
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20131214/67e25d57/attachment.sig>
More information about the Haskell-Cafe
mailing list