[Haskell-cafe] FFI, C/C++ and undefined references

Bulat Ziganshin bulat.ziganshin at gmail.com
Wed Jan 13 06:33:35 EST 2010


Hello DNM,

Wednesday, January 13, 2010, 8:57:45 AM, you wrote:

> Note: I'm relatively new to Haskell, and my knowledge of C and C++ is
> basically pretty
> minimal -- I can read, modify and compile C/C++ programs (usually).

1. you use too much unsafePerformIO. since you need newCString, i
suggest you to declare C functions as returning IO a so your code
will be

unsafePerformIO$ do
  withCString str $ \c_str -> do
  c_function c_str ...

2. if your function returns Ptr a - then hold in haskell types this Ptr a.
no need to convert it back and forth to ForeignPtr

3. why c_dlm is FunPtr in your definition? it should be

foreign import ccall "srilm.h deleteLM"
    c_dlm :: Ptr Ngram -> IO ()

4. i don't looked in your code but if C functions defines
*modifiable* datastructure - you should use it at Haskell side via
imperatiove functions, i.e. those with return type IO a. using
unsafePerformIO in this case will lead to Haskell compiler will
consider this datatype as permanent and reorder operations on the will

so,

> data NGModel = NGModel {ng :: !(Ptr Ngram)}

> foreign import ccall "srilm.h bldLM"
>     c_blm :: CInt -> CString -> IO (Ptr Ngram)

> foreign import ccall "srilm.h deleteLM"
>     c_dlm :: Ptr Ngram -> IO ()

> foreign import ccall "srilm.h getSeqProb" 
>     c_ngramProb :: Ptr Ngram -> CString -> CUInt -> CUInt -> IO CFloat

> scoreSequence :: NGModel -> Int -> [String] -> IO Float
> scoreSequence ngram order seq = do
>       withCString (unwords seq) $ \stringSeq -> do
>       sc <- c_ngramProb (ng ngram) stringSeq (fromIntegral order) (fromIntegral $ length seq)
>       return (realToFrac sc)

and so on



-- 
Best regards,
 Bulat                            mailto:Bulat.Ziganshin at gmail.com



More information about the Haskell-Cafe mailing list