指向类和结构体的指针
指向类的指针
class PointerTestClass {
var intNum = 3
var another = 56
var another1 = 59
}
下面是验证代码
let pointer: UnsafeMutablePointer<PointerTestClass> = UnsafeMutablePointer.allocate(capacity: 3)
let testInstance = PointerTestClass()
pointer.initialize(repeating: testInstance, count: 3)
// ⚠️ 下面这个会报错,因为还处于 uninit 状态
// pointer.assign(repeating: testInstance, count: 3)
testInstance.intNum = 4
//改了一个,所有的都会改,因为指向了同一个地址。
expect(pointer.pointee.intNum).to(equal(4))
expect(pointer[1].intNum).to(equal(4))
expect(pointer[2].intNum).to(equal(4))
// 证明是同一个地址
var instanceAddress: String!
withUnsafeBytes(of: testInstance, { (rawBuffer) in
let data = Data.init(bytes: rawBuffer.baseAddress!, count: rawBuffer.count)
instanceAddress = data.hexView
})
(0..<3).forEach({ (offset) in
pointer.advanced(by: offset).withMemoryRebound(to: UInt8.self, capacity: 8, { (uInt8Pointer) in
let data = Data.init(bytes: uInt8Pointer, count: 8)
expect(data.hexView).to(equal(instanceAddress))
})
})

指向struct 的指针
struct 定义如下:
struct PointerTestStruct {
var intNum = 3
var another = 56
var another1 = 59
}
下面是验证代码
let pointer: UnsafeMutablePointer<PointerTestStruct> = UnsafeMutablePointer.allocate(capacity: 3)
var testInstance = PointerTestStruct()
//可以用assign,因为是 trival type
pointer.assign(repeating: testInstance, count: 3)
testInstance.intNum = 4
//改了一个,其他的不会受影响,因为是不同的实例。
expect(pointer.pointee.intNum).to(equal(3))
expect(pointer[1].intNum).to(equal(3))
expect(pointer[2].intNum).to(equal(3))
var memory: String!
let stride = MemoryLayout.stride(ofValue: testInstance)
withUnsafeBytes(of: testInstance, { (rawBuffer) in
let data = Data.init(bytes: rawBuffer.baseAddress!, count: rawBuffer.count)
memory = data.hexView
})
(0..<3).forEach({ (offset) in
pointer.advanced(by: offset).withMemoryRebound(to: UInt8.self, capacity: stride, { (uInt8Pointer) in
let data = Data.init(bytes: uInt8Pointer, count: stride)
expect(data.hexView).toNot(equal(memory))
})
})

下起雨,也要勇敢前行