[Haskell-cafe] Could FFI support pass-by-value of structs?

John Meacham john at repetae.net
Tue Jun 23 18:25:12 EDT 2009

On Tue, Jun 16, 2009 at 10:48:19AM -0300, Maurí­cio wrote:
> It's not usual, but it is allowed to have values of
> structs passed between functions directly instead of
> using pointers:
> /*****/
> struct ex {
>     int x;
>     int y;
>     int z;
> };
> ex example_functions (ex p)
> {
>   (...)
> }
> /*****/
> Would it be possible to allow that in Haskell FFI
> by, say, allowing any instance of Storable to be
> used in a 'foreign' declaration? Like:

There are a couple problems with this. First, the storage layout for a
given C struct may be radically different depending on the back end,
even sometimes depending on the operating system. So you can't write a
portable Storable instance. 

The other problem is that the storage layout isn't enough to use structs
as arguments as the calling conventions also come into play. Some
calling conventions want structs expanded and places on the stack,
others want a pointer to some stack allocated data, returning a struct
may or may not create a hidden first argument. Now, Haskell compilers
already have to tackle calling conventions for basic types, so it is
entirely plausable to solve this, the question is, is it worth the
effort? anything you write will end up not being portable anyway because
it depends on the structure layout.

The end result being, structure passing is complicated, so if you need
to interface to a library that has pre-defined structeres, use hsc2hs to
manually peek and poke into the correct offsets, it will make things
easier and be more portable.


John Meacham - ⑆repetae.net⑆john⑈ - http://notanumber.net/

More information about the Haskell-Cafe mailing list