[Haskell-cafe] Re: Marshalling arrays without flakiness? (poke example)

Maurí­cio CA mauricio.antunes at gmail.com
Thu Oct 29 17:11:33 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).

Here is an example with poke. It's completely useless, except for
demonstration :) You have a global variable in C that receives
data in a struct, and a 'print' function that prints it.

*** C header: ***

   #define NPOWERS 6
   typedef struct {
     double number;
     double negpowers[NPOWERS];
   } power_struct;
   extern power_struct np;
   void print_np (void);

*** C definition: ***

   power_struct np;
   void print_np (void)
   {
     int i;
     printf("\n");
     printf ("Negative powers of %g: \n",np.number);
     for (i=0;i<=NPOWERS;i++) printf("  %g",np.negpowers[i]);
     printf("\n");
   }

*** Binding module, with hsc2hs macros: ***

   #starttype power_struct
   #field number , CDouble
   #array_field negpowers , CDouble
   #stoptype

   #globalvar np , <power_struct>
   #ccall print_np , IO ()

*** Haskell calls: ***

   main = (flip mapM_) [2..5] $ \n ->
    poke p'np (C'power_struct {
      c'power_struct'number = n,
      c'power_struct'negpowers = iterate (/n) (1/n)
     }) >> c'print_np

*** Output ***

   Negative powers of 2:
     0.5  0.25  0.125  0.0625  0.03125  0.015625  0
   Negative powers of 3:
     0.333333  0.111111  0.037037  0.0123457  0.00411523  0.00137174  0
   Negative powers of 4:
     0.25  0.0625  0.015625  0.00390625  0.000976562  0.000244141  0
   Negative powers of 5:
     0.2  0.04  0.008  0.0016  0.00032  6.4e-05  0


Best,
Maurício



More information about the Haskell-Cafe mailing list