有没有办法从 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/