How does one use pass by reference functions using the ffi?
Manuel Chakravarty
chak at cse.unsw.edu.au
Sun Jan 25 01:35:25 EST 2004
David Sankel wrote:
> Say I have a function somewhere in c land with the following declaration:
>
> void doStuff( int &a, int &b);
>
> What would the appropriate Haskell wrapper for this function look like?
It'll be
doStuffC :: Ptr Int -> Ptr Int -> IO ()
which really is a purely syntactic translation of the type
of the C function.
> I'm looking to construct a haskell function of the type:
>
> doStuff :: Int -> Int -> IO( (Int,Int) )
You will need to do the work of allocating temporary storage
and passing pointers to that storage manually unless you use
one of the FFI tools (eg, c2hs
<http://www.cse.unsw.edu.au/~chak/haskell/c2hs/> or
GreenCard). Doing it manually isn't quite as bad as it
might sound at first, as the FFI libraries contain
convenience functions for this type of situation:
http://haskell.org/ghc/docs/latest/html/libraries/base/Foreign.Marshal.Utils.html#v%3Awith
So you get
doStuff x y =
with x $ \xPtr ->
with y $ \yPtr -> do
doStuffC xPtr yPtr -- calling into C land
x' <- peek xPtr
y' <- peek yPtr
return (x', y')
(The `with' brackets ensure proper deallocation of the
temporary storage in a stack-like manner.)
Good Luck!
Manuel
More information about the FFI
mailing list