[Haskell-cafe] Writing a Storable instance for a C union
Simon Marechal
simon at banquise.net
Sat Dec 14 18:22:12 UTC 2013
On 12/14/2013 05:46 PM, Nikita Karetnikov wrote:
> Yes, but I also want to poke, so SomeUnion must be an instance of
> Storable. Could you show how to define it properly or provide a
> workaround?
You do not need to store the "key", or have an additional C'MyStruct
data type, as you already have this information in Haskell :
data SomeUnion = UnionFoo C'Foo
| UnionWord64 Word64
| UnionVoid (Ptr ())
deriving (Show, Eq)
instance Storable SomeUnion where
sizeOf _ = 12
alignment _ = 4
peek p = do
v0 <- peekByteOff p 0
case v0 of
1 -> UnionFoo `fmap` peekByteOff p 4
4 -> UnionWord64 `fmap` peekByteOff p 4
20 -> UnionVoid `fmap` peekByteOff p 4
_ -> fail "you should probably handle this case"
poke p (UnionFoo v1) = pokeByteOff p 0 1 >> pokeByteOff p 4 v1
poke p (UnionWord64 v1) = pokeByteOff p 4 1 >> pokeByteOff p 4 v1
poke p (UnionVoid v1) = pokeByteOff p 20 1 >> pokeByteOff p 4 v1
More information about the Haskell-Cafe
mailing list