美文网首页
Swift - UnsafePointer

Swift - UnsafePointer

作者: ienos | 来源:发表于2022-07-11 15:08 被阅读0次
  • UnsafeBufferPointer 常用于集合数组类
let ptr = UnsafeBufferPoint(start: &person, count: 1)
let basePtr = ptr.baseAddress // 首地址
basePtr?.pointee
  • unsafeBitCast(person, to: UnsafePointer<Person>.self) 强转数据类型

  • UnsafeRawPointer(bitPattern: 0x0000600000c54060) 通过地址获取指针

// 取出地址中的值
ptr.load(as: T.Type)
// 地址偏移
ptr.advanced(by: Int)
// 存储
ptr.storeBytes(of: T, toByteOffset: Int, as: T)
  • UnsafeMutablePointer<Int>.allocate(capacity: 1) / UnsafePointer<Int>
let intPointer = UnsafeMutablePointer<Int>.allocate(capacity: 1) 
intPointer.initialize(to: 10) // 初始化
intPointer.pointee = 4 // 赋值
intPointer.deallocate() // 释放
  • withUnsafeMutablePointer(to: &intValue, { }) 获取指针
intValue = try! withUnsafeMutablePointer(to: &intValue, { (ptr: UnsafeMutablePointer<Int>) throws -> Int in
    ptr.pointee += 1
    return ptr.pointee
})

相关文章

网友评论

      本文标题:Swift - UnsafePointer

      本文链接:https://www.haomeiwen.com/subject/ldsnbrtx.html