扩展眼界Swift开发那些事

Swift-06.指针(UnsafePointer)

2020-11-30  本文已影响0人  Fight_ing
Swift中也有专门的指针类型,这些都被定性为“Unsafe”(不安全的)。
常见的有以下4种类型:
    var age = 10
    func test1(_ ptr: UnsafeMutablePointer<Int>) {
        ptr.pointee += 10 
    }
    func test2(_ ptr: UnsafePointer<Int>) { 
        print(ptr.pointee)
    }
    test1(&age)
    test2(&age) // 20
    print(age) // 20

    var age = 10
    func test3(_ ptr: UnsafeMutableRawPointer) {
        ptr.storeBytes(of: 20, as: Int.self) 
    }
    func test4(_ ptr: UnsafeRawPointer) { 
        print(ptr.load(as: Int.self))
    }
    test3(&age)
    test4(&age) // 20
    print(age) // 20
var age = 11
var ptr1 = withUnsafeMutablePointer(to: &age) { $0 } 
var ptr2 = withUnsafePointer(to: &age) { $0 } 
ptr1.pointee = 22
print(ptr2.pointee) // 22
print(age) // 22

var ptr3 = withUnsafeMutablePointer(to: &age) { UnsafeMutableRawPointer($0) } 
var ptr4 = withUnsafePointer(to: &age) { UnsafeRawPointer($0) } 
ptr3.storeBytes(of: 33, as: Int.self)
print(ptr4.load(as: Int.self)) // 33
print(age) // 33
// UnsafeRawPointer(bitPattern:)函数用来生成指向某一地址的指针
var ptr = UnsafeRawPointer(bitPattern: 0x100001234)

class Person {}
// 类似于 *p = person
var person = Person()
// p = &person, p是person变量的地址值
var ptr = withUnsafePointer(to: &person) { UnsafeRawPointer($0) }
// ptr.load(as: UInt.self) 类似于 *p, 取出地址中存储的值,也就是Person实例在堆上的地址值
var heapPtr = UnsafeRawPointer(bitPattern: ptr.load(as: UInt.self)) 
print(heapPtr!)
上一篇 下一篇

猜你喜欢

热点阅读