How does one use pass by reference functions using the ffi?

Glynn Clements glynn.clements at virgin.net
Sun Jan 25 03:10:35 EST 2004


David Sankel wrote:

> Hello FFI experts,
> 
>   Say I have a function somewhere in c land with the following declaration:
> 
> void doStuff( int &a, int &b);

That isn't C. Are you referring to C++ references, or did you mean:

	void doStuff(int *a, int *b);

?

>   What would the appropriate Haskell wrapper for this function look like? 
> I'm looking to construct a haskell function of the type: 
> 
> doStuff :: Int -> Int -> IO( (Int,Int) )

The direct translation would be:

	Ptr CInt -> Ptr CInt -> IO ()

Higher level interfaces, such as the one which you suggest, could be
built upon that, e.g.:

	import Foreign.C(CInt)
	import Foreign.Ptr(Ptr)
	import Foreign.Marshal.Utils(with)
	import Foreign.Storable(peek)
	
	foreign import ccall doStuff :: Ptr CInt -> Ptr CInt -> IO ()
	
	doStuff' :: Int -> Int -> IO (Int,Int)
	doStuff' x y = do
	 with (fromIntegral x) $ \px ->
	  with (fromIntegral y) $ \py -> do
	   doStuff px py
	   x' <- peek px
	   y' <- peek py
	   return (fromIntegral x', fromIntegral y')

-- 
Glynn Clements <glynn.clements at virgin.net>


More information about the FFI mailing list