swift Class的内存布局
class Human {
//8 type or isa
//retainCount
var age: Int?//16
var name: String?//16
var nicknames: [String] = [String]()
//返回指向 Human 实例头部的指针
func headPointerOfClass() -> UnsafeMutablePointer<Int8> {
let opaquePointer = Unmanaged.passUnretained(self as AnyObject).toOpaque()
let mutableTypedPointer = opaquePointer.bindMemory(to: Int8.self, capacity: MemoryLayout<Human>.stride)
return UnsafeMutablePointer<Int8>(mutableTypedPointer)
}
}
MemoryLayout<Human>.size //8
let human = Human()
let arrFormJson = ["goudan","zhaosi", "wangwu"]
//拿到指向 human 堆内存的 void * 指针
let humanRawPtr = UnsafeMutableRawPointer(human.headPointerOfClass())
//nicknames 数组在内存中偏移 48byte 的位置(8+8+16+16)
let humanNickNamesPtr = humanRawPtr.advanced(by: 48).assumingMemoryBound(to: Array<String>.self)
print(human.nicknames)
//[]
humanNickNamesPtr.initialize(to: arrFormJson)
print(human.nicknames)
human.nicknames //["goudan","zhaosi", "wangwu"]
let retainCount = humanRawPtr.advanced(by: 8).assumingMemoryBound(to: Int8.self)
print(retainCount.pointee)