Description
The Haskell FFI cannot handle pure struct arguments in foreign declarations, only struct pointers. Unfortunately, I deal with several libraries with functions that expect pure structs as arguments. As a simplified example:
typedef struct {
int x;
int y;
} coord_t;
int coord_x(coord_t c) {
return c.x;
}
There isn't any way for Haskell to call this directly. Instead, I'd first have to create another C file with a function that wraps coord_x
:
int wrap_coord_x(coord_t *c) {
return coord_x(*c);
}
This gets to be pretty tedious and mechanical, which made me wonder if this process could be automated via build-tools. I know c2hs
already generates *.chs.h
files for CPP pragmas and other miscellanoues C code, so I wonder if *.chs.c
files could also be generated with the implementations of wrap_*
functions.
I'm not sure what the syntax for such as feature would look like—perhaps something like this:
{#fun pure wrap coord_x as coordX { `CoordPtr' } -> `Int' #}
data Coord
{#pointer *coord_t as CoordPtr -> Coord #}
that could automatically generate this Haskell FFI code:
foreign import ccall safe "<module>.chs.h wrap_coord_x"
coordX'_ :: CoordPtr -> CInt
where wrap_coord_x
is defined in <module>.chs.h
and implemented in <module>.chs.c
? There'd probably need to be further name-mangling in case there's already a wrap_coord_x
defined as well.