[Haskell-cafe] [ANN] Haskell FFI Tutorial

Evan Laforge qdunkan at gmail.com
Thu Nov 13 05:00:53 UTC 2014


Doesn't hsc2hs give you the size with #size?  I feel like I'm not
understanding your approach.

I was thinking of using language-c to parse the .h file, and generate
an hs file:

structs.h:

struct example { int a; char b; }

Structs_generated.hs:

module X.Y.Structs_generated where
import X.Y.Structs (Example)
poke_example_a :: (#type int) -> Ptr Example -> IO ()
poke_example_b :: (#type char) -> Ptr Example -> IO ()
example_alignment = 4
example_size = 5

You have to provide the Structs module that exports the types, this
just makes sure that the pokes only work on the intended types.  Then
the poke functions tie the struct field name and its type and the
record type.

For the #type I could either then run this through hsc2hs to get the
types, or just have a hardcoded mapping.  #type sees through typedefs
and the like, but all it can see is size and signedness.

While I'm at it I could add foreign declarations for the function
prototypes, and solve the problem of keeping those in sync.

Another thing I like about this approach is that you import a
generated file, but all the marshaling work is done in a plain .hs
file.  Putting code in a .hsc breaks ghci since you need to regenerate
after each edit, and it breaks tools that want to parse hs source.

I'm sure it's way more complicated than it seems though, things inevitably are.

I read the c2hs docs but I kind of don't really get it yet.  I should
just download a project that uses it and see how it works.

On Wed, Nov 12, 2014 at 5:03 PM, Richard A. O'Keefe <ok at cs.otago.ac.nz> wrote:
> The fact that the sizes of things can vary between compilation
> environments on the same host is one of the reasons tools like
> hsc2hs are hard.

That just means you need the same compiler flags for the C side as for
the haskell side, right?  Presumably that's not too hard because you
build it all together.  Or is there some further complexity?


More information about the Haskell-Cafe mailing list