总得说点什么,不能只贴代码呐
/// Swift里面也有专门的指针类型,这些都被定性为 `Unsafe`(不安全的), 常见的4种类型 /// UnsafePointer<Pointee> 类似于 const Pointee * /// UnsafeMutablePointer<Pointee> 类似于 Pointee * /// UnsafeRawPointer 类似于 const void * 指向类型不确定 /// UnsafeMutableRawPointer 类似于 void * 指向类型不确定 var age = 10 func test1(_ ptr: UnsafeMutablePointer<Int>) {// int * ptr.pointee = 20 } func test2(_ ptr: UnsafePointer<Int>) { // const int * print("test2", ptr.pointee) } func test3(_ ptr: UnsafeRawPointer) { // const void * print("test3", ptr.load(as: Int.self)) } func test4(_ ptr: UnsafeMutableRawPointer) { // void * ptr.storeBytes(of: 30, as: Int.self) } //func test3(_ num: inout Int) { // //} test1(&age) test2(&age) test3(&age) test4(&age) //test3(&age) print(age) /// 使用场景 /// OC -> BOOL * /// Swift -> UnsafeMutablePointer<ObjeCBool> var arr = NSArray(objects: 11, 22, 33, 44) arr.enumerateObjects { (element, idx, stop) in if idx == 2 { stop.pointee = true } print(idx, element) } /// 获得指向某个变量的指针 /// withUnsafePointer 跟body返回类型一样 var ptrAge1 = withUnsafePointer(to: &age){ $0 } print(ptrAge1.pointee) var ptrAge2 = withUnsafeMutablePointer(to: &age) { (pointer) -> UnsafeMutablePointer<Int> in return pointer } var ptrAge3 = withUnsafePointer(to: &age, { UnsafeRawPointer($0) }) var ptrAge4 = withUnsafeMutablePointer(to: &age, { UnsafeMutableRawPointer($0) }) ptrAge4.storeBytes(of: 40, as: Int.self) print(age) /// 获取指向堆空间的指针 class Person { var age = 0 deinit { print("Person deinit") } } var person = Person() var ptrPerson1 = withUnsafePointer(to: &person, { $0 }) //保存person对象的地址值 print(ptrPerson1.pointee.age) /// 创建指针 var mPtr = malloc(16) mPtr?.storeBytes(of: 11, as: Int.self) mPtr?.storeBytes(of: 22, toByteOffset: 8, as: Int.self) print(mPtr?.load(as: Int.self)) print(mPtr?.load(fromByteOffset: 8, as: Int.self)) free(mPtr) var allPtr = UnsafeMutableRawPointer.allocate(byteCount: 16, alignment: 1) allPtr.storeBytes(of: 11, as: Int.self) allPtr.storeBytes(of: 22, toByteOffset: 8, as: Int.self) allPtr.advanced(by: 8) //移动8个字节,返回一个新指针 allPtr.deallocate() var capPtr = UnsafeMutablePointer<Int>.allocate(capacity: 3) capPtr.initialize(to: 11) capPtr.successor().initialize(to: 22) capPtr.successor().successor().initialize(to: 33) print(capPtr.pointee) print((capPtr + 1).pointee) print((capPtr + 2).pointee) print(capPtr[0]) print(capPtr[1]) print(capPtr[2]) capPtr.deinitialize(count: 3) capPtr.deallocate() var pPtr = UnsafeMutablePointer<Person>.allocate(capacity: 3) pPtr.initialize(to: Person()) (pPtr + 1).initialize(to: Person()) (pPtr + 2).initialize(to: Person()) pPtr.deinitialize(count: 3) pPtr.deallocate()
--EOF--
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于