swift - 如何将数据转换为 UnsafePointer<UInt8>?

标签 swift unsafe-pointers

在 Swift 中,我想传递 data 类型的数据缓冲区(名为 Data )到一个 C 函数(名为 do_something ),它采用 UnsafePointer<UInt8> 类型的指针.
下面的代码示例是否正确?如果是这样,在这种情况下可以使用 assumingMemoryBound(to:)而不是 bindMemory(to:capacity:) ?

data.withUnsafeBytes { (unsafeBytes) in
  let bytes = unsafeBytes.baseAddress!.assumingMemoryBound(to: UInt8.self)
  do_something(bytes, unsafeBytes.count)
}

最佳答案

正确的方法是使用bindMemory() :

data.withUnsafeBytes { (unsafeBytes) in
    let bytes = unsafeBytes.bindMemory(to: UInt8.self).baseAddress!
    do_something(bytes, unsafeBytes.count)
}
assumingMemoryBound()仅当内存已绑定(bind)到指定类型时才必须使用。
关于这个主题的一些资源:
  • UnsafeRawPointer Migration Guide
  • UnsafeRawPointer API
  • 关于swift - 如何将数据转换为 UnsafePointer<UInt8>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63566744/

    相关文章:

    ios - 带有 UIRefreshControl 的 TableView 在重新加载时似乎有点故障?

    ios - CGColor - 从彼此重叠的两个 UIView 中确定混合颜色

    c# - 使用 LayoutKind.Explicit 绕过 "unsafe"指针是否合法?

    memory - 为什么在使用不安全的 Rust 访问超出范围的变量时没有段错误?

    go - 将字符串复制到字符串结构中

    swift - 启用混合导致 renderPipelineState 无法在 MetalKit MTKView 中构建

    ios - 6.0.1 和表更改 "UILabel? does not have a member named ' 文本”

    ios - 在 UITableView 集合上水平滚动

    go - 需要帮助来理解 Go 语言中的垃圾收集

    swift3 - Swift 3 - 将 c 结构 sockaddr_in 转换为 CFData