Search code examples
haskellffibytestring

Ptr Word8 to ByteString


I have an FFI call returning some data bytes (not a CString). Currently, I am using something like the following:

import qualified Data.ByteString as BS

BS.pack <$> mapM (peekElem ptr) [0 .. n - 1]

Is there a more efficient approach to this? Googling around seems to point towards using Data.ByteString.Internal, but that seems to be frowned upon (binding to internal interfaces). In fact they don't seem to offer docs for the internal module anymore. Is there a more efficient portable approach? I constantly run into this problem when dealing with bytes from FFI. I just want:

ptrToBs :: Ptr Word8 -> Int -> IO ByteString
ptrToBs buf n = ... -- totally fine if it makes a copy of the buffer

(I did check Hoogle first.)

Maybe I am using the wrong type for "raw bytes to be consumed by Binary.Get or some other decoding package later"?


Solution

  • It seems you want to avoid CString for the (in my opinion excellent) reason that they are null-terminated. The more principled CStringLen does not have this weakness, and so packCStringLen :: CStringLen -> IO ByteString should be suitable for your task.