Are peekCString and peekCStringLen lazy?

三世轮回 提交于 2019-12-12 11:23:28

问题


I have a C function that creates a null terminated string and returns a pointer to it, there is also corresponding deallocation function.

foreign import ccall unsafe "get_str" getStr :: IO CString
foreign import ccall unsafe "free_str" freeStr :: CString -> IO ()

I want to create a Haskell String from the returned CString, and free CString as soon as possible.

do cStr <- getStr
   str <- peekCString cStr
   freeStr cStr
   -- here str is used

Is it safe to free cStr before str is used? In other words, does peekCString create Haskell String all at once, or is it created lazily?


回答1:


peekCString is strict -- it doesn't suspend the loop via unsafeInterleaveIO, for example, so once you have the head of the string, you've definitely already computed the tail. Here's the implementation:

peekCAString cp = do
  l <- lengthArray0 nUL cp
  if l <= 0 then return "" else loop "" (l-1)
  where
    loop s i = do
        xval <- peekElemOff cp i
        let val = castCCharToChar xval
        val `seq` if i <= 0 then return (val:s) else loop (val:s) (i-1)


来源:https://stackoverflow.com/questions/1739186/are-peekcstring-and-peekcstringlen-lazy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!