[Haskell-cafe] Writing a Storable instance for a C union

Simon Marechal simon at banquise.net
Sat Dec 14 07:58:04 UTC 2013


On 12/14/2013 12:24 AM, Nikita Karetnikov wrote:
> 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.)

It's as simple as :

peek p = do
	v0 <- peekByteOff p 0
	case v0 of
		1 -> MyStruct <$> peekByteOff p 4
		2 -> FooStruct <$> peek...

But this function can only have a single type, hence my suggestion
that you should create a union type to represent the C union :

type SomeUnion = MyStruct Byte | FooStruct Integer | ...


More information about the Haskell-Cafe mailing list