MemoryLayout
可以使用MemoryLayout获取数据类型占用的内存大小
enum Password {
case number(Int, Int, Int, Int) // 32
case other
}
MemoryLayout<Password>.size // 33
MemoryLayout<Password>.stride // 40
MemoryLayout<Password>.alignment // 8
inout传递参数是传递地址
var number = 10
func test(_ num: Int) {
}
test(number)
0x100000f5e <+78>: movq -0x30(%rbp), %rdi
0x100000f62 <+82>: callq 0x100000f70 ; TestSwift.test(Swift.Int) -> () at main.swift:24
var number = 10
func test(_ num: inout Int) {
}
test(&number)
0x100000f47 <+55>: leaq 0x10ca(%rip), %rdi ; TestSwift.number : Swift.Int
0x100000f4e <+62>: callq 0x100000f70 ; TestSwift.test(inout Swift.Int) -> () at main.swift:24
- 如果实参有物理内存地址,且没有设置属性观察器
直接将实参的内存地址传入函数(实参进行引用传递) - 如果实参是计算属性 或者 设置了属性观察器
采取了Copy In Copy Out的做法
- 调用该函数时,先复制实参的值,产生副本【get】
- 将副本的内存地址传入函数(副本进行引用传递),在函数内部可以修改副本的值
- 函数返回后,再将副本的值覆盖实参的值【set】
总结:inout的本质就是引用传递(地址传递)
枚举关联值存储在内存中
func testEnum() {
enum TestEnum {
case test1(Int, Int, Int)
case test2(Int, Int)
case test3(Int)
case test4(Bool)
case test5
}
// 1个字节存储成员值
// N个字节存储关联值(N取占用内存最大的关联值),任何一个case的关联值都共用这N个字节
// 共用体
// 小端:高高低低
// 01 00 00 00 00 00 00 00
// 02 00 00 00 00 00 00 00
// 03 00 00 00 00 00 00 00
// 00
// 00 00 00 00 00 00 00
var e = TestEnum.test1(1, 2, 3)
print(Mems.ptr(ofVal: &e))
// 04 00 00 00 00 00 00 00
// 05 00 00 00 00 00 00 00
// 00 00 00 00 00 00 00 00
// 01
// 00 00 00 00 00 00 00
e = .test2(4, 5)
print(Mems.memStr(ofVal: &e))
// 06 00 00 00 00 00 00 00
// 00 00 00 00 00 00 00 00
// 00 00 00 00 00 00 00 00
// 02
// 00 00 00 00 00 00 00
e = .test3(6)
// 01 00 00 00 00 00 00 00
// 00 00 00 00 00 00 00 00
// 00 00 00 00 00 00 00 00
// 03
// 00 00 00 00 00 00 00
e = .test4(true)
// 00 00 00 00 00 00 00 00
// 00 00 00 00 00 00 00 00
// 00 00 00 00 00 00 00 00
// 04
// 00 00 00 00 00 00 00
e = .test5
}
对象的堆空间申请过程
- Class.__allocationg_init()
- libswiftCore.dylib: swift_allocObject
- libswiftCore.dylib: swift_slowAlloc
- libsystem_mallic.dylib: malloc
字符串的内存
// 字符串长度 <= 0xF,字符串内容直接存放在str1变量的内存中
var str1 = "0123456789"
// 字符串长度 > 0xF,字符串内容存放在__TEXT.cstring中(常量区)
// 字符串的地址值信息存放在str2变量的后8个字节中
var str2 = "0123456789ABCDEF"
// 由于字符串长度 <= 0xF,所以字符串内容依然存放在str1变量的内存中
str1.append("ABCDE")
// 开辟堆空间
str1.append("F")
// 开辟堆空间
str2.append("G")
Array的内存
var arr = [1, 2, 3, 4]
指针
Swift中也有专门的指针类型,这些都被定性为“Unsafe”(不安全的),常见的有以下4种类型
- UnsafePointer<Pointee> 类似于 const Pointee *
- UnsafeMutablePointer<Pointee> 类似于 Pointee *
- UnsafeRawPointer 类似于 const void *
- UnsafeMutableRawPointer 类似于 void *
var age = 10
func test1(_ ptr: UnsafeMutablePointer<Int>) {
ptr.pointee += 10 }
func test2(_ ptr: UnsafePointer<Int>) { print(ptr.pointee)
}
test1(&age)
test2(&age) // 20
print(age) // 20
var age = 10
func test3(_ ptr: UnsafeMutableRawPointer) {
ptr.storeBytes(of: 20, as: Int.self) }
func test4(_ ptr: UnsafeRawPointer) { print(ptr.load(as: Int.self))
}
test3(&age)
test4(&age) // 20
print(age) // 20
var arr = NSArray(objects: 11, 22, 33, 44)
arr.enumerateObjects { (obj, idx, stop) in
print(idx, obj)
if idx == 2 { // 下标为2就停止遍历
stop.pointee = true
}
}
var arr = NSArray(objects: 11, 22, 33, 44)
for (idx, obj) in arr.enumerated() {
print(idx, obj)
if idx == 2 {
break
}
}
获取某个变量的指针
var age = 11
var ptr1 = withUnsafeMutablePointer(to: &age) { $0 } var ptr2 = withUnsafePointer(to: &age) { $0 } ptr1.pointee = 22
print(ptr2.pointee) // 22
print(age) // 22
var ptr3 = withUnsafeMutablePointer(to: &age) { UnsafeMutableRawPointer($0) } var ptr4 = withUnsafePointer(to: &age) { UnsafeRawPointer($0) } ptr3.storeBytes(of: 33, as: Int.self)
print(ptr4.load(as: Int.self)) // 33
print(age) // 33
获取指向堆空间实例的指针
class Person {}
var person = Person()
var ptr = withUnsafePointer(to: &person) { UnsafeRawPointer($0) } var heapPtr = UnsafeRawPointer(bitPattern: ptr.load(as: UInt.self)) print(heapPtr!)
创建指针
var ptr = UnsafeRawPointer(bitPattern: 0x100001234)
// 创建
var ptr = malloc(16)
// 存
ptr?.storeBytes(of: 11, as: Int.self)
ptr?.storeBytes(of: 22, toByteOffset: 8, as: Int.self)
// 取
print((ptr?.load(as: Int.self))!) // 11
print((ptr?.load(fromByteOffset: 8, as: Int.self))!) // 22 // 销毁
free(ptr)
var ptr = UnsafeMutableRawPointer.allocate(byteCount: 16, alignment: 1) ptr.storeBytes(of: 11, as: Int.self)
ptr.advanced(by: 8).storeBytes(of: 22, as: Int.self)
print(ptr.load(as: Int.self)) // 11
print(ptr.advanced(by: 8).load(as: Int.self)) // 22
ptr.deallocate()
var ptr = UnsafeMutablePointer<Int>.allocate(capacity: 3)
ptr.initialize(to: 11)
ptr.successor().initialize(to: 22)
ptr.successor().successor().initialize(to: 33)
print(ptr.pointee) // 11
print((ptr + 1).pointee) // 22
print((ptr + 2).pointee) // 33
print(ptr[0]) // 11
print(ptr[1]) // 22
print(ptr[2]) // 33
ptr.deinitialize(count: 3)
ptr.deallocate()
class Person {
var age: Int
var name: String
init(age: Int, name: String) {
self.age = age
self.name = name
}
deinit {
print(name, "deinit")
}
}
var ptr = UnsafeMutablePointer<Person>.allocate(capacity: 3) ptr.initialize(to: Person(age: 10, name: "Jack"))
(ptr + 1).initialize(to: Person(age: 11, name: "Rose"))
(ptr + 2).initialize(to: Person(age: 12, name: "Kate"))
// Jack deinit
// Rose deinit
// Kate deinit
ptr.deinitialize(count: 3)
ptr.deallocate()
指针之间的切换
var ptr = UnsafeMutableRawPointer.allocate(byteCount: 16, alignment: 1)
ptr.assumingMemoryBound(to: Int.self).pointee = 11
(ptr + 8).assumingMemoryBound(to: Double.self).pointee = 22.0 print(unsafeBitCast(ptr, to: UnsafePointer<Int>.self).pointee) // 11
print(unsafeBitCast(ptr + 8, to: UnsafePointer<Double>.self).pointee)
// 22.0
ptr.deallocate()
- unsafeBitCast是忽略数据类型的强制转换,不会因为数据类型的变化而改变原来的内存数据
类似于C++中的reinterpret_cast
class Person {}
var person = Person()
var ptr = unsafeBitCast(person, to: UnsafeRawPointer.self)
print(ptr)