[Haskell-cafe] FFI and struct arguments

Bayley, Alistair Alistair.Bayley at invesco.com
Thu Jul 17 11:37:18 EDT 2008

> From: haskell-cafe-bounces at haskell.org 
> [mailto:haskell-cafe-bounces at haskell.org] On Behalf Of Duncan Coutts
> Sent: 17 July 2008 12:46
> On Wed, 2008-07-16 at 22:45 -0300, Felipe Lessa wrote:
> > Hi,
> > 
> > I tried googling and searching the haskellwiki about this but wasn't
> > lucky enough. My question is: is there a way to send struct 
> arguments
> > to C functions via the FFI or do I need to create a C 
> wrapper? I guess
> > there isn't, and while I can live without it, I'd like to leave no
> > doubt.
> If the struct is passed by reference of course then you're 
> fine, but if
> it's by value then you need a C wrapper. The reason is because it's
> beyond the scope of the FFI to know the structure layout and 
> how to map
> that to haskell types. That's the domain of FFI 
> pre-processors. However
> I don't know of any FFI pre-processors that help in this 
> case. Passing C
> structs by value seems to be pretty rare in exported C APIs.

hsc2hs can help a bit (I haven't used the other FFI tools, so don't take
this as an endorsement of hsc2hs over them). You could create a wrapper
that marshals your Vector to a vector struct like this:

---- .hsc file:

#include <vect.h>  -- whatever header contains your C vector struct

data VectorC = Ptr ()  -- opaque data type, like void*

-- your Haskell vector
data Vector = Vector Float Float

vector2cvect :: Vector -> IO VectorC
vector2cvect (Vector x y) = do
  ptr <- mallocBytes #{size vect}
  pokeByteOff #{offset vect, x} x
  pokeByteOff #{offset vect, x} x
  return ptr

cvect2Vector :: VectorC -> IO Vector
cvect2Vector ptr = do
  x <- peekByteOff ptr #{offset vect, x}
  y <- peekByteOff ptr #{offset vect, y}
  return (Vector x y)

-- inline your *vect->vect wrapper (ends up in generated .c file)
#def void funcWrapper(vect *v) { func(*v); }

foreign import stdcall funcWr unsafe "funcWrapper" :: VectorC -> IO ()

main = do
  vc <- vector2cvect (Vector 3 4)
  funcWr vc
  free vc
Confidentiality Note: The information contained in this message,
and any attachments, may contain confidential and/or privileged
material. It is intended solely for the person(s) or entity to
which it is addressed. Any review, retransmission, dissemination,
or taking of any action in reliance upon this information by
persons or entities other than the intended recipient(s) is
prohibited. If you received this in error, please contact the
sender and delete the material from any computer.

More information about the Haskell-Cafe mailing list