[Haskell-cafe] Re: Begginer question about alignment in Storable

Michael D. Adams mdmkolbe at gmail.com
Thu Nov 20 15:34:39 EST 2008


On Thu, Nov 20, 2008 at 11:26 AM, Mauricio <briqueabraque at yahoo.com> wrote:
>> (...)   But the  major advantage  of hsc2hs  is that  if  your C
>> struct changes or you use a different C compiler, the allignment
>> and size as well as the offsets used in peek and poke will still
>> be correct since the compiler will calculate it for you. (...)
>>
>> And you  wanted to write  a storable instance.  With  hsc2hs you
>> would write it like this: (...)
>
> Thanks! This is actually a really  nice tutorial! Do you mind if I
> try to find a place for it in the wiki?

Go right ahead(*).  Of course if you put that in, you should note that
the #{alignment foo} syntax is not currently built-in to hsc2hs.  You
have to add the following line to your haskell source file to add the
alignment syntax:

#let alignment t = "%lu", (unsigned long)offsetof(struct {char x__; t
(y__); }, y__)

For completeness I should note that if you had a string field (e.g.
struct { char c_string_field[MAX_LEN]; }) you would have to do it a
little different.  For example in peek:
  peek ptr = do
    s <- peekCString $ #{ptr c_type,c_string_field} ptr
    return (Foo s)

Then in poke you would do:
  poke ptr (Foo s) = do
    withCStringLen (take maxLen value) $ uncurry (copyArray $ #{ptr
c_type,c_string_field} ptr)
    where maxLen = #{const MAX_LEN}

Note the use of #{ptr} instead of #{peek} since we want the address of
the c_string_field rather than it's value.  Unfortunately for the
"struct { char *c_string_field; }" style there is no good general
solution because you have to worry about allocating memory to have
c_string_field point to.

I'll leave figuring out #{enum}, but it can also be quite helpful in
translating C enums/defines into Haskell.

Michael D. Adams

(*) For the lawyers: I hereby place that and these code snippet in the
public domain or the nearest legal equivalent for those countries that
don't have a legal concept of public domain.


More information about the Haskell-Cafe mailing list