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

时间:2020-08-24 18:29:32

标签: swift unsafe-pointers

在Swift中,我想将类型为data的数据缓冲区(命名为Data)传递给采用类型为do_something的指针的C函数(命名为UnsafePointer<UInt8>)。

下面的代码示例正确吗?如果是这样,在这种情况下可以使用assumingMemoryBound(to:)代替bindMemory(to:capacity:)吗?

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

1 个答案:

答案 0 :(得分:2)

正确的方法是使用bindMemory()

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

assumingMemoryBound()仅在内存已绑定到指定的类型时使用。

有关此主题的一些资源: