swift3.0 如何操作指针

1、不涉及到类型的转换。
取地址& , 函数参数列表中加inout, 调用函数使用取地址&, 做实参传递。 函数里面,可以直接使用变量读取, 修改。

2、能够表现的类型T的转换, 用UnsafeMutablePointer, UnsafePointer

func t(block : ((UnsafeMutablePointer<Int>)->())?) {
    let p = UnsafeMutablePointer<Int>.allocate(capacity: 1)
    p.initialize(to: 50)
    print(p)
    print(p.pointee)
    block?(p)
    print(p)
    print(p.pointee)
}
t { (p) in
    p.pointee = 99
}
func t2(p : inout UnsafeMutablePointer<Int>) -> (){
    p.pointee = 333
    
    let p2 = UnsafeMutablePointer<Int>.allocate(capacity: 1)
    p2.initialize(to: 444)
    p = p2
}
var p = UnsafeMutablePointer<Int>.allocate(capacity: 1)
p.initialize(to: 111)
print(p.pointee)
t2(p: &p)
print(p)
print(p.pointee)

3、C类型的转换, 用Unmanaged
CFArray

4、函数类型的转换,函数类型转换为闭包

int fff(int (f)(int x,int y)) {
    return f(1,2)
}
let callback: @convention(c) (Int32, Int32) -> Int32 = {
    (x, y) -> Int32 in
    return x + y
}

5、不能够表现的类型的转换,用OpaquePointer

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容