[Haskell-cafe] Re: Marshalling arrays without flakiness?

Maurí­cio CA mauricio.antunes at gmail.com
Thu Oct 29 12:57:55 EDT 2009


> I would like to know whether there is a good way to marshal the
> following structure to C without using pointer arithmetic done
> by a programmer (as opposed to a tool).
> 
> typedef struct{
>     double a[10];
>     double b[10];
>     double b[10];
> } foo;

With my my 'bindings-common' package it's done like this:

#starttype struct foo
#array_field a , CDouble
#array_field b , CDouble
#array_field c , CDouble
#stoptype

There's no problem if you change the order of the fields, or
ommit one of them. To be consistent with Marshal.Array, Haskell
datatype fields corresponding to a, b and c will be lists. If you
try to poke some value with list fields containing more than 10
elements, only the first 10 will be stored. That size is detected
automatically.

If you want to check how does the code you write compare to
the Haskell code you get, you can check this binding to posix
<utsname.h>:

http://bitbucket.org/mauricio/bindings-posix/src/tip/src/Bindings/Posix/Sys/Utsname.hsc
http://hackage.haskell.org/packages/archive/bindings-posix/1.2/doc/html/Bindings-Posix-Sys-Utsname.html

Based on this example, this is how you would write code to tell
you the name of your OS. (This is a 'peek' example, but 'poke'
code would be similar.)

   name :: IO String
   name =   alloca $ \ptr -> do
     c'uname ptr
     uts <- peek ptr
     let original = takeWhile (/= 0) $ c'utsname'sysname uts
     return $ map (toEnum . fromEnum) original

Here is some documentation on that package:

http://bitbucket.org/mauricio/bindings-common/wiki/Home

Hope this helps.

Best,
Maurício



More information about the Haskell-Cafe mailing list