If I have access to the C struct definition in the header files but want to define my storable instance manually without using something like hsc2hs, how do I find the alignment value?
Also could a wrong alignment value cause a crash or just affect performance?
Edit: Apologies, I misread the question and thought you were asking about doing this with hsc2hs, not without. Incorrect alignment can lead to incorrect data and cause crashes (consider if you're marshalling an array of structs), so you really should use something portable.
According to the FFI cookbook, you can define
#let alignment t = "%lu", (unsigned long)offsetof(struct {char x__; t (y__); }, y__)
which is then used as
instance Storable Struct where
alignment _ = #{alignment my_struct}
sizeOf _ = #{size my_struct}
The alignment
keyword should be available in ghc > 7.2.1, so you wouldn't need to define it yourself with very new ghc's.
With gcc, you can find the alignment per __alignof__ (type)
more. The value is, however, architecture-dependent, so for portability, you should determine the alignment on each machine by a macro. Which means that hsc2hs is probably the better way.
I think the wrong alignment can lead to crashes, but I don't know for sure.
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