haskell - 如何获得 ByteString 的 Ptr?

标签 haskell bytestring

有没有办法从 ByteString 对象中提取指向内存的底层直接指针?
编译器说,我目前的方法是不正确的。

getPtr :: ByteString -> Ptr Word8
getPtr (PS ptr _ _) = ptr

最佳答案

使用 unsafeUseAsCString 来自 Data.ByteString.Unsafe .它有类型:

ByteString -> (CString -> IO a) -> IO a

您可以使用 unsafeUseAsCString bs return简单地获取指针,但这是非常不安全的,因为 ByteString不保证不会移动,内存可能会在 CString -> IO a 之后的任何时候被释放函数终止,因此您应该只访问其中的指针;它在内部使用 Foreign.ForeignPtr.withForeignPtr ,它固定内存,因此如果发生 GC,它就不会移动。根据文档:

The memory may freed at any point after the subcomputation terminates, so the pointer to the storage must not be used after this.



除非 ByteString,否则字符串也不会以 null 结尾。碰巧是,它的类型为 CString (即 Ptr CChar )而不是 Ptr Word8 , 但您可以使用 castPtr来自 Foreign.Ptr解决这个问题,如果这是一个问题。

关于haskell - 如何获得 ByteString 的 Ptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20180764/

相关文章:

haskell - float 问题

performance - Haskell 中 hFlush 的高 CPU 使用率

arrays - 在 Haskell 中存储和排序矩形数据的最佳方法是什么?

performance - Haskell 和 C++ 之间的 Coin Change 性能差异

haskell - :reload and run :main as a single command in GHCi?的正确方法是什么

haskell - 在运行时动态生成 Haskell 类型?

optimization - GHC 中的嵌套解包

string - Haskell 如何创建 Word8?

haskell - 将字节字符串部分解码为文本

haskell - 有效地将 ByteString 转换为十六进制表示