Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
FFI example
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
{-# 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)
float mean(int* arr, unsigned n) {
int acc = 0;
for (unsigned i = 0; i < n; ++i) {
acc += arr[i];
}
return (float) acc / (float) n;
}
float mean(int*, unsigned);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.