peekCString 和 peekCStringLen 是懒惰的吗?

发布于 2024-08-11 16:46:30 字数 459 浏览 5 评论 0原文

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

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

我想从返回的 CString 创建一个 Haskell String,并尽快释放 CString。

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

在使用 str 之前释放 cStr 安全吗?换句话说,peekCString是一次性创建Haskell String,还是延迟创建?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

往昔成烟 2024-08-18 16:46:30

peekCString 是严格的——例如,它不会通过 unsafeInterleaveIO 暂停循环,所以一旦你有了字符串的头部,你肯定已经计算了尾部。这是实现:

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 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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文