Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the Storable typeclass do in Haskell

Tags:

haskell

I have been reading some documentation on Haskell's C FFI. And I've just encountered a typeclass called Storable, which I don't understand very well.

Are instances of this typeclass, those types are supposed to have a "pointer" to them while interfacing with the C code?

Also what do the individual functions sizeOf, alignment, peek, poke do? It seems peek and poke are used to read data from or write data to a place in memory pointed to by Ptr a. Is this right?

But I don't know what sizeOf and alignment mean at all. Can someone give examples to clarify their use?

like image 385
smilingbuddha Avatar asked Sep 10 '16 00:09

smilingbuddha


1 Answers

Haskell stores values in memory in a way that is very incompatible to C. As a result, it is not possible to call a C function from haskell and pass to it haskell values directly. Instead, you have to create a copy of the value, but not an exact copy, but rather in a format that is understood by C. That's what Storable does. So it essentially provides way to serialize haskell values to a C friendly format (e.g. think C structs). It also supports the opposite operation, it can deserialize values. This is useful when a C function is called from haskell and returns a complex (i.e. non primitive) value.

The serialization/deserialization happens with the help of poke/peek. sizeOf returns the byte size of the C representation of the value. Note that this mechanism only works for values that have a C representation of fixed size (e.g. structs). It does not support things like C strings, they are treated differently. As for alignment, it used to ensure that memory allocations done in the haskell land satisfy the platform's alignment requirements.

like image 134
redneb Avatar answered Oct 31 '22 11:10

redneb