Are peekCString and peekCStringLen lazy?

I have a C function that creates a string with a terminating zero and returns a pointer to it, there is also a corresponding release 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 release the CString as soon as possible.

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

Is it safe to free cStr before using str? In other words, does peekCString create a Haskell String right away or is it lazy to create?

+4
source share
1 answer

peekCString is strict - it does not pause the loop through unsafeInterleaveIO, for example, therefore, as soon as you have the head of the string, you definitely already calculated the tail. Here's the implementation:

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

Source: https://habr.com/ru/post/982604/


All Articles