Search code examples
pointershaskellnullbytestring

How to create a Ptr Word8 for ByteString


create, from Data.ByteString.Internal, states that it needs a Ptr Word8 in order to create a ByteString. I'm guessing this is like a reference to the head of the bytestring or something. However, I'm not sure what I should use to create a new pointer - I'm fairly sure it's not done properly with nullPtr.


Solution

  • No, create gives you a pointer to a memory to fill:

    create :: Int -> (Ptr Word8 -> IO ()) -> IO ByteString
    

    The first argument is the length of bytestring to create, the second is a function, that fills the bytestring. Basically create allocates memory buffer of the specified size, then calls the function with the pointer to the buffer. Usage example:

    > create 5 $ \ptr -> pokeArray ptr [65, 66, 67, 68, 69]
    "ABCDE"