with を使って C の関数へポインタ渡しをする

Foreign.Marshal.UtilsのwithはC の関数への引数をポインタ渡しするときに使う。

-- ghc --make -Wall frexp.hs  test.c  -o frex
{-# LANGUAGE ForeignFunctionInterface #-}
 
import Foreign.Ptr
import Foreign.C.Types
import Foreign.Marshal.Utils

foreign import ccall unsafe "test" c_test :: Ptr CInt -> Ptr CInt -> IO CInt

func :: CInt -> CInt -> IO CInt
func x y = with x  (\xptr -> with y (\yptr -> c_test xptr yptr))

main :: IO()
main = print =<< func 2 3 -- => 8
  • test.c
int test(int *a, int *b){ return (*a + (*b *2)); }