考虑以下代码片段
import qualified Foreign.Concurrent
import Foreign.Ptr (nullPtr)
main :: IO ()
main = do
putStrLn "start"
a <- Foreign.Concurrent.newForeignPtr nullPtr $
putStrLn "a was deleted"
putStrLn "end"
它产生以下输出:
start
end
我本来希望在..a was deleted
之后的某个地方看到“”start
我不知道发生了什么事。我有几个猜测:
- 程序结束时垃圾收集器不会收集剩余的对象
putStrLn
完成后停止工作main
。(顺便说一句,我尝试了与外国进口相同的事情puts
并得到了相同的结果)- 我的理解
ForeignPtr
不足 - GHC 错误?(环境:GHC 6.10.3,英特尔 Mac)
当使用Foreign.ForeignPtr.newForeignPtr
而不是Foreign.Concurrent.newForeignPtr
它似乎工作时:
{-# LANGUAGE ForeignFunctionInterface #-}
import Foreign.C.String (CString, newCString)
import Foreign.ForeignPtr (newForeignPtr)
import Foreign.Ptr (FunPtr)
foreign import ccall "&puts" puts :: FunPtr (CString -> IO ())
main :: IO ()
main = do
putStrLn "start"
message <- newCString "a was \"deleted\""
a <- newForeignPtr puts message
putStrLn "end"
输出:
start
end
a was "deleted"