Skip to content
Create a gist now

Instantly share code, notes, and snippets.

FFI example
name: ffi
license: GPL-3
license-file: LICENSE
author: Mikhail Glushenkov
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
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
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.