問題のライブラリが見つからない場合は、自分でライブラリを作成するか(明らかなオプションであり、簡単ではありません)、必要な関数のバインディングを作成することができます。たとえば、sprintf
sprintfのみを許可する制限付きバインディングは次のようになります。
Double.hs:
{-# INCLUDE "double.h" #-}
{-# LANGUAGE ForeignFunctionInterface #-}
module Double (cPrintf) where
import Foreign
import Foreign.C.Types
import System.IO.Unsafe
import qualified Data.ByteString as B
foreign import ccall "double.h toString"
c_toString :: CDouble -> (Ptr Word8) -> CInt -> IO CInt
buf = unsafePerformIO $ mallocBytes 64
cPrintf :: Double -> B.ByteString
cPrintf n = B.pack $ unsafePerformIO $ do
len <- c_toString (realToFrac n) buf 64
peekArray (fromIntegral len) buf
double.h:
int toString(double a, char *buffer, int bufferLen);
double.c:
#include <stdio.h>
#include "double.h"
int toString(double a, char *buffer, int bufferLen) {
return snprintf(buffer, bufferLen, "%f", a);
}
次のようにビルドします。
gcc -c double.c
ghc --make Main.hs double.o