Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the alignment value when defining a storable instance

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?

like image 253
Tim Matthews Avatar asked Dec 02 '11 01:12

Tim Matthews


2 Answers

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.

like image 126
John L Avatar answered Oct 13 '22 22:10

John L


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.

like image 4
Daniel Fischer Avatar answered Oct 14 '22 00:10

Daniel Fischer