ma1*_*w28 5 unsafe-pointers swift
在 Swift 中,我想将data类型为 的数据缓冲区(名为 )传递给采用类型为指针的DataC 函数(名为) 。do_somethingUnsafePointer<UInt8>
下面的代码示例正确吗?如果是这样,在这种情况下可以使用assumingMemoryBound(to:)代替 吗bindMemory(to:capacity:)?
data.withUnsafeBytes { (unsafeBytes) in
let bytes = unsafeBytes.baseAddress!.assumingMemoryBound(to: UInt8.self)
do_something(bytes, unsafeBytes.count)
}
Run Code Online (Sandbox Code Playgroud)
正确的方法是使用bindMemory():
data.withUnsafeBytes { (unsafeBytes) in
let bytes = unsafeBytes.bindMemory(to: UInt8.self).baseAddress!
do_something(bytes, unsafeBytes.count)
}
Run Code Online (Sandbox Code Playgroud)
assumingMemoryBound()仅当内存已绑定到指定类型时才必须使用。
有关此主题的一些资源: