peekCString和peekCStringLen是否懒惰? [英] Are peekCString and peekCStringLen lazy?

查看:137
本文介绍了peekCString和peekCStringLen是否懒惰?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C函数,它创建一个以null结尾的字符串并返回一个指向它的指针,还有相应的deallocation函数。

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 ()

我想从返回的CString中创建一个Haskell字符串,并且尽快

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

使用str之前释放cStr是否安全?换句话说,peekCString是一次创建Haskell String还是它是懒惰创建的?

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?

推荐答案

peekCString是严格的 - 它例如,不会通过unsafeInterleaveIO挂起循环,因此,一旦拥有了字符串的头部,您就已经计算出了尾部。这是实现:

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)

这篇关于peekCString和peekCStringLen是否懒惰?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆