withMemoryRebound(to:capacity:_:)
T
类型的实例。声明
func withMemoryRebound<T, Result>(
to type: T.Type,
capacity count: Int,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result
返回值
body
闭包参数的返回值(如果有)。
参数
type
临时绑定此指针引用的内存的类型。
T
类型的布局必须与指针的Pointee
类型兼容。count
重新绑定区域中
T
的实例数。body
一个闭包,它将类型化指针指向与此指针相同的内存,仅绑定到类型
T
。闭包的指针参数仅在闭包执行期间有效。如果body
有返回值,则该值也用作withMemoryRebound(to:capacity:_:)
方法的返回值。pointer
指针临时绑定到
T
。
详述
当您有一个指向绑定到一种类型的内存的指针并且您需要将该内存作为另一种类型的实例来访问时,请使用此方法。以T
类型访问内存需要将内存绑定到该类型。一个内存位置一次只能绑定到一种类型,因此在不首先重新绑定内存的情况下访问与不相关类型相同的内存是未定义的。
从此指针开始并覆盖 T
实例的 count
跨度的内存区域必须绑定到 Pointee
。重新绑定区域内的T
的任何实例都可以被初始化或未初始化。 Pointee
的每个实例与 T
的给定实例重叠应具有相同的初始化状态(即已初始化或未初始化)。访问其底层 Pointee
存储处于混合初始化状态的 T
应为未定义行为。
以下示例临时将 UInt64
指针的内存重新绑定到 Int64
,然后访问有符号整数的属性。
let uint64Pointer: UnsafePointer<UInt64> = fetchValue()
let isNegative = uint64Pointer.withMemoryRebound(
to: Int64.self, capacity: 1
) {
return $0.pointee < 0
}
因为在 body
闭包执行时,该指针的内存不再绑定到它的 Pointee
类型,所以不要使用 body
中的原始指针访问内存。相反,使用 body
闭包的指针参数来访问内存中的值作为类型 T
的实例。
执行 body
后,此方法将内存重新绑定回原始的 Pointee
类型。
可用版本
相关用法
- Swift UnsafePointer ...(_:)用法及代码示例
- Swift UnsafePointer ..<(_:)用法及代码示例
- Swift UnsafePointer ...(_:_:)用法及代码示例
- Swift UnsafePointer ..<(_:_:)用法及代码示例
- Swift UnsafePointer用法及代码示例
- Swift UnsafeMutableRawPointer ..<(_:_:)用法及代码示例
- Swift UnsafeBufferPointer randomElement()用法及代码示例
- Swift UnsafeRawBufferPointer.Iterator dropFirst(_:)用法及代码示例
- Swift UnsafeMutablePointer allocate(capacity:)用法及代码示例
- Swift UnsafeRawBufferPointer.Iterator max()用法及代码示例
- Swift UnsafeBufferPointer min(by:)用法及代码示例
- Swift UnsafeMutableBufferPointer allocate(capacity:)用法及代码示例
- Swift UnsafeRawBufferPointer shuffled(using:)用法及代码示例
- Swift UnsafeBufferPointer prefix(upTo:)用法及代码示例
- Swift UnsafeMutableRawPointer ...(_:_:)用法及代码示例
- Swift UnsafeMutableBufferPointer prefix(through:)用法及代码示例
- Swift UnsafeRawBufferPointer isEmpty用法及代码示例
- Swift UnsafeMutableRawBufferPointer shuffle()用法及代码示例
- Swift UnsafeRawPointer advanced(by:)用法及代码示例
- Swift UnsafeRawBufferPointer enumerated()用法及代码示例
- Swift UnsafeBufferPointer firstIndex(of:)用法及代码示例
- Swift UnsafeMutableBufferPointer map(_:)用法及代码示例
- Swift UnsafeMutablePointer withMemoryRebound(to:capacity:_:)用法及代码示例
- Swift UnsafeRawBufferPointer subscript(_:)用法及代码示例
- Swift UnsafeBufferPointer map(_:)用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 UnsafePointer withMemoryRebound(to:capacity:_:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。