指向类和结构体的指针

Posted huahuahu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了指向类和结构体的指针相关的知识,希望对你有一定的参考价值。

指向类的指针

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

技术图片?

以上是关于指向类和结构体的指针的主要内容,如果未能解决你的问题,请参考以下文章

结构体里面包含指向本结构体的指针的写法

c++的类和结构体是啥关系

结构体指针

c语言中2个结构体的头指针相等,会不会把其中一个覆盖了

结构体指针在使用完free后,该指针所指向的内存区域是啥,这个指针是变成了NULL,还是野指针。

链表使用类和结构体的区别?