Skip to content

Instantly share code, notes, and snippets.

@Voker57
Last active December 17, 2015 07:58
Show Gist options
  • Select an option

  • Save Voker57/5576287 to your computer and use it in GitHub Desktop.

Select an option

Save Voker57/5576287 to your computer and use it in GitHub Desktop.
Sample Haskell module compiling into .so
{-# LANGUAGE ForeignFunctionInterface #-}
module A (encodeCrockford, decodeCrockford) where
import Foreign.Marshal.Utils
import Foreign.Ptr
import Foreign.C.String
import Foreign.C.Types
import Foreign.Marshal.Array
import Codec.Crockford
import Codec.Text.Raw
import Codec.Utils
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
encodeCrockford :: CString -> IO CString
encodeCrockford cs = do
os <- peekArray0 0 cs
let bs = BS8.pack $ Codec.Crockford.encode $ fromOctets 256 $ map (fromIntegral) os
BS.useAsCString bs (\ cs' -> do
len <- lengthArray0 0 cs'
csNew <- mallocArray0 len
copyArray csNew cs' (len + 1)
return csNew
)
decodeCrockford :: CString -> IO CString
decodeCrockford cs = do
pt <- new (fromIntegral 0 :: CInt)
s <- peekCString cs
let bs = BS.pack $ maybe [] (toOctets 256) $ Codec.Crockford.decode s
BS.useAsCString bs (\ cs' -> do
len <- lengthArray0 0 cs'
csNew <- mallocArray0 len
copyArray csNew cs' (len + 1)
return csNew
)
foreign export ccall encodeCrockford :: CString -> IO CString
foreign export ccall decodeCrockford :: CString -> IO CString
clean:
rm -f *_stub* *.hi *.o *.so
rnacrockford.so: A.hs
ghc -package Crypto -package crockford -package bytestring -c -O A.hs
ghc -package Crypto -package crockford -package bytestring -optc-O -I. -L. -optc-Wl,-Bstatic -optc-Wl,-Bdynamic -optl '-shared' -no-hs-main A.o -o rnacrockford.so
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment