在Haskell中将Vector转换为ByteString

我很困惑我如何将Data.Vector.Storable的向量转换为ByteString.我猜我错过了一些相当明显的东西.

我需要将它转换为ByteString,因为我想通过网络发送它,使用Network.Socket.ByteString,它似乎是最有效的数据结构.

如何编写代码来编写函数

writeToByteString :: Vector Int -> ByteString
writeToByteString v = 

非常感谢.

最佳答案 这取决于你真正想要实现的目标.正如bheklilr所提到的,Int表示是特定于平台的.

但在引擎盖下,可存储的矢量是一块记忆.要获取其内容,请使用unsafeToForeignPtr0.这是一个例子:

import qualified Data.Vector.Storable as V
import qualified Data.ByteString as BS

import Foreign

main :: IO ()
main = do
  let v = V.generate 10 id :: V.Vector Int
      (fptr, len) = V.unsafeToForeignPtr0 v
  print v
  bs <- withForeignPtr fptr $\ptr ->
    BS.packCStringLen (castPtr ptr, len * sizeOf (undefined :: Int))
  print $BS.unpack bs

输出:

fromList [0,1,2,3,4,5,6,7,8,9]
[0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0]
点赞