指向类和结构体的指针

指向类的指针

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))
                    })
                })

转载于:https://www.cnblogs.com/huahuahu/p/zhi-xiang-lei-he-jie-gou-ti-de-zhi-zhen.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值