Created
October 22, 2012 13:25
-
-
Save 23Skidoo/3931496 to your computer and use it in GitHub Desktop.
FFI example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
float mean(int* arr, unsigned n) { | |
int acc = 0; | |
for (unsigned i = 0; i < n; ++i) { | |
acc += arr[i]; | |
} | |
return (float) acc / (float) n; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
float mean(int*, unsigned); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment