3

While using c2hsc and hsc2hs saves me a lot of work, I've run into some trouble when trying to create bindings for C unions.


For example, given the C structure

typedef struct {
      int tag;
      union {
            char a;
            double b;
      } v;
} sum_t;

c2hsc creates the following code for me:

#starttype sum_t
#field tag , CInt
#field v , 
#stoptype

where the v field is generated empty. Going further down the toolchain via hsc2hs yields the incorrect

data C'sum_t = C'sum_t{
  c'sum_t'tag :: CInt,
  c'sum_t'v :: 
}

The questions now are

  1. What is the correct way to write the .hsc code manually so I can work with the bindings?
  2. Is there a way I can make c2hsc do this automatically?
David
  • 8,275
  • 5
  • 26
  • 36
  • 3
    Given that the `hsc2hs` codebase no mention of unions at all I suspect it's not implemented. Plus, unions are inherently unsafe, so it's not obvious how one would translate them into algebraic data types. To do it safely one needs the discriminator as well, which is an entity outside the union. – Rufflewind Jan 04 '15 at 15:32
  • Your best bet would probably be to write the functions to construct and manipulate these in C yourself, and then use those from the Haskell side. But I know nothing about the FFI. – dfeuer Jan 04 '15 at 15:34

1 Answers1

0

c2hsc just generates bindings-dsl macros. Using the documentation there, you should be able to figure out how to write these directly. Consider something like...

#starttype struct sum_t
#field tag , CInt
#field v.a , CChar
#field v.b , CDouble
#stoptype

The documentation goes on to describe how to manipulate unions using pointers.

sclv
  • 38,665
  • 7
  • 99
  • 204