美文网首页
Swift指针

Swift指针

作者: 逃之不桃 | 来源:发表于2018-06-25 14:36 被阅读0次

    Swift指针为结构体表示分为两种,一种是带有格式的,一种是不带格式的。

    如:

    UnsafePointer这种是带格式的,带格式的指针实现了Pointee,所以可以使用.pointee来取值;

    UnsafeRawPointer这种是不带格式的 ,可以理解为一段的纯粹的二进制,要对UnsafeRawPointer这种指针取值,需要将其转化为带格式的指针。

    带有mutale的为值可变指针,即可以对指针对应的值赋值,不带的mutale的为只读指针

    指针初始化
    注意:使用alloc初始化的指针,释放的时候都要调用deallocate来释放

    方法一:

    
    var str = "test"
    
    let pointer = withUnsafePointer(to: &str, {
    
          return $0
    
    })
    
    

    得到的是一个UnsafePointer

    方法二:

    
    let pointer = UnsafeMutablePointer.allocate(capacity: 8)
    

    得到的是一段长度为8个字节的指针UnsafeMutablePointer

    如果要得到一个空指针怎么办呢?

    在oc中我们通常会用:(float *)NULL来表示

    swift 提供了类似的函数使用:UnsafePointer(bitPattern: 0)

    方法三:

    先初始化无格式指针,再将无格式指针转化为有格式指针

    
    let rawPointer = calloc(8, MemoryLayout<UInt8>.size)!
    
    let pointer = rawPointer.assumingMemoryBound(to: UInt32)
    
    

    方法四:

    使用&,只能用于函数传递,例如:

    
    var testStr = "test"
    
    test(&testStr)
    
    print(testStr)
    
    func test(_ pointer: UnsafeMutablePointer) {
    
          pointer.pointee = "changed"
    
    }
    
    

    指针类型变化

    如果我有一个UnsafeMutablePointer<UInt8>想按照UnsafeMutablePointer<UInt32>读取怎么办?

    
    let point = UnsafeMutablePointer<UInt8>.allocate(capacity: 8)
    
     let newPointer = point.withMemoryRebound(to: UInt32, capacity: 2, {
    
           return $0
    
      })
    
    

    赋值和取值

    
            var testStr = "123456789"
    
            let testP = withUnsafeMutablePointer(to: &testStr, {
    
                return $0
    
            })
    
            print(testP.pointee)
    
            testP.pointee = "abcdefg"
    
            print(testP)
    
    

    data与bytes

    
            let str = "aaaaaaabbbbbbbccccccc"
    
            var data = str.data(using: .utf8)!
    
            data.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in
    
                var bytesStart = bytes
    
                for _ in 0..
    
                    print(bytesStart.pointee)
    
                    bytesStart += 1
    
                }
    
            }
    
    

    UnsafeBufferPointer(类似于bytes),用法与UnsafePointer差不多,实现了Sequence

    
            let str = "aaaaaaabbbbbbbccccccc"
    
            var data = str.data(using: .utf8)!
    
            let pointer = UnsafeMutableBufferPointer.allocate(capacity: data.count)
    
            data.copyBytes(to: pointer)
    
            for i in 0..10
    
                print(pointer[i])
    
            }
    
    

    相关文章

      网友评论

          本文标题:Swift指针

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