Ptr Word8 到 ByteString

Ptr Word8 to ByteString

我有一个 FFI 调用返回一些数据字节(不是 CString)。 目前,我正在使用如下内容:

import qualified Data.ByteString as BS

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

是否有更有效的方法?谷歌搜索似乎指向使用 Data.ByteString.Internal,但这似乎不受欢迎(绑定到内部接口)。事实上 they don't seem 不再为内部模块提供文档。 有没有更有效的可移植方法? 在处理来自 FFI 的字节时,我经常 运行 遇到这个问题。我只想:

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

(我确实先检查了 Hoogle。)

也许我为 "raw bytes to be consumed by Binary.Get or some other decoding package later" 使用了错误的类型?

您似乎想避免 CString 因为(在我看来非常好)它们以 null 结尾的原因。比较有原则的CStringLen没有这个弱点,所以packCStringLen :: CStringLen -> IO ByteString应该适合你的任务。