How to find the alignment value when defining a stored instance

If I have access to the definition of the C structure in the header files, but you want to define my persistent instance manually without using something like hsc2hs, how can I find the alignment value?

Also, can an incorrect alignment value cause a crash or just affect performance?

+7
source share
2 answers

Edit: Sorry, I misunderstood the question and thought you asked for it with hsc2hs, but not without. Incorrect alignment can lead to incorrect data and cause crashes (think if you are building an array of structures), 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 won’t need to define it yourself with the very new ghc.

+7
source

With gcc, you can find alignment by __alignof__ (type) more . The value, however, depends on the architecture, so for portability you must define the alignment on each machine with a macro. This means that hsc2hs is probably the best way.

I think misalignment can lead to crashes, but I don't know for sure.

+4
source

All Articles