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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With