[Haskell-cafe] ByteString FFI

Duncan Coutts duncan.coutts at worc.ox.ac.uk
Sun Nov 12 14:44:49 EST 2006


On Sun, 2006-11-12 at 10:49 -0800, Donn Cave wrote:
> How do people like to set up their foreign I/O functions to return
> ByteStrings?  I was a little stumped over this yesterday evening,
> while trying to write ` recv :: Socket -> Int -> Int -> ByteString '
> 
> Doc says `Byte vectors are encoded as strict Word8 arrays of bytes,
> held in a ForeignPtr, and can be passed between C and Haskell with
> little effort.'  Which sounds perfect - I'm always up for `little effort'!
> 
> CString doesn't seem like the right thing for socket results, because
> the data shouldn't be NUL-terminated, and I might want to realloc when
> the returned data doesn't fill the buffer.  I don't see any other
> Ptr-related function or constructor in the documentation - am I missing
> something there?

packCStringLen :: CStringLen -> ByteString

(type CStringLen = (Ptr CChar, Int))

http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-ByteString.html#v%3ApackCStringLen

So if you know the length and the pointer to the beginning of the buffer
then it's just packCStringLen (ptr, len)

Of course you're not allowed to change the buffer after this, if you are
using a mutable buffer then you'll have to make a copy:

copyCStringLen :: CStringLen -> IO ByteString

Duncan



More information about the Haskell-Cafe mailing list