プログラミング

HaskelとC言語の連携

HaskelとC言語との連携もそれほど大変なものではありません。私はほとんどHaskelでの開発をしていないので,Haskelの記法には違和感があります。

#!/bin/bash
gcc --shared -fPIC -o libadd.so -xc - << EOS
int add(int x, int y) { return x + y; }
EOS

cat << EOF > Main.hs
module Main where
import Foreign.C.Types

foreign import ccall "add" c_add :: CInt -> CInt -> CInt
cAdd x y = fromIntegral $ c_add (fromIntegral x) (fromIntegral y)

main :: IO ()
main = do putStrLn "START"
          putStrLn ("100 + 200 = " ++ (show(cAdd 100 200)))
          putStrLn "END"
EOF

ghc -L. -ladd Main.hs
if [ $? -eq 0 ]; then
  ./Main
fi