public
Created

FFI example

  • Download Gist
Main.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
{-# LANGUAGE ForeignFunctionInterface #-}
 
module Main
where
 
import Foreign.C
import Foreign.Marshal.Safe
import Foreign.Ptr
import Foreign.Storable
 
foreign import ccall unsafe "mean" c_mean :: Ptr CInt -> CUInt -> IO CFloat
 
main :: IO ()
main = do
buf <- mallocBytes (bufSize * sizeOfCInt)
fillBuffer buf 0
m <- c_mean buf (fromIntegral bufSize)
print $ realToFrac m
where
sizeOfCInt = sizeOf (0::CInt)
bufSize = 100
 
fillBuffer :: Ptr CInt -> Int -> IO ()
fillBuffer buf i | i == bufSize = return ()
| otherwise = do
poke buf 123
fillBuffer (buf `plusPtr` sizeOfCInt) (i+1)
ffi.cabal
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
name: ffi
version: 0.1.0.0
license: GPL-3
license-file: LICENSE
author: Mikhail Glushenkov
maintainer: the.dead.shall.rise@gmail.com
category: Testing
build-type: Simple
cabal-version: >=1.8
extra-source-files: cbits/mean.h
 
executable ffi
main-is: Main.hs
build-depends: base ==4.5.*
c-sources: cbits/mean.c
cc-options: -std=c99
include-dirs: cbits
mean.c
C
1 2 3 4 5 6 7 8 9
float mean(int* arr, unsigned n) {
int acc = 0;
 
for (unsigned i = 0; i < n; ++i) {
acc += arr[i];
}
 
return (float) acc / (float) n;
}
mean.h
C
1
float mean(int*, unsigned);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.