美文网首页
siwft指针

siwft指针

作者: alex_zn | 来源:发表于2018-08-01 17:47 被阅读0次
    swift 指针

    UnsafePointer,UnsafeMutablePointer ,可变和不可变指针可以相互转变,

    初始化一块内存
    let p1 = UnsafeMutablePointer<Int>.allocate(capacity: 0)
    p1.initialize(to: 1)
    // get set
    p1.pointee = 2
    
    // 相互转化
    let a:Int = p1.pointee
    //let pointA:UnsafeMutablePointer = &a
    
    // UnsafeMutablePointer -> UnsafePointer
    let pa = UnsafePointer<Int>.init(p1)
    // get only
    pa.pointee
    

    UnsafeMutableRawPointer,原生指针类型,创建后需要通过bindMemory绑定值类型

    
    // UnsafeMutableRawPointer
    var intSize = MemoryLayout<CLongDouble>.size
    var aRawP = UnsafeMutableRawPointer.allocate(byteCount: intSize, alignment: MemoryLayout<Int>.size)
    // 绑定值类型
    let rp = aRawP.bindMemory(to: CLongDouble.self, capacity: 1)
    rp.pointee = 12.12
    
    rp.deallocate()
    

    UnsafeMutableBufferPointer 指向数组的指针,可以对指针遍历,移动

    // 直接对指针变换操作
    var b = 0
    var nb = withUnsafeMutablePointer(to: &b) { (point) -> UnsafeMutablePointer<Int> in
        
        let size = MemoryLayout<Int>.size
        size.advanced(by: 1)
        // 返回该指针的指针偏移量
        let moveP = point + 1
        moveP.pointee = 2
        moveP.pointee
        
        return moveP
    }
    nb.pointee
    
    // UnsafeMutableBufferPointer
    var array:[Double] = [11, 22, 33, 44, 55]
    let aPtr = UnsafeMutableBufferPointer<Double>.init(start: &array, count: array.count)
    for item in aPtr.enumerated() {
        item.offset
        item.element
    }
    let newArr = aPtr.map { (v) -> Int in
        return Int(v)
    }
    
    // 获取指针对应值
    aPtr.baseAddress?.advanced(by: 1).pointee
    aPtr.baseAddress?.advanced(by: 2).pointee
    

    相关文章

      网友评论

          本文标题:siwft指针

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