Skip to content

Instantly share code, notes, and snippets.

@23Skidoo
Created October 22, 2012 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 23Skidoo/3931496 to your computer and use it in GitHub Desktop.
Save 23Skidoo/3931496 to your computer and use it in GitHub Desktop.
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