peekCString 和 peekCStringLen 是懒惰的吗?
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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: