问题描述
在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)
}
解决方法
正确的方法是使用bindMemory()
:
data.withUnsafeBytes { (unsafeBytes) in
let bytes = unsafeBytes.bindMemory(to: UInt8.self).baseAddress!
do_something(bytes,unsafeBytes.count)
}
assumingMemoryBound()
仅在内存已绑定到指定的类型时使用。
有关此主题的一些资源: