我会说,如果缺少相关库,那么您可以自己编写一个(显而易见的选择,并不容易),或者为所需的函数编写一个绑定。例如,只sprintf
允许 sprintf 的受限绑定加倍:
双.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
双.h:
int toString(double a, char *buffer, int bufferLen);
双.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