0%

指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/// 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–