1.1 swift中使用UnsafePoint结构体代替直接操作指针。通过pointee访问其引用的数据。
ex-1.1 :
var m = "12"
let pointer = withUnsafePointer(to: &m) { (pointer) -> UnsafePointer<String> in
return pointer
}
print(pointer.pointee) //输出 "12"
1.2 swift 指针分类
1.2.1 UnsafePointer,UnsafeMutablePointer 指定类型的指针结构体
1.2.2 UnsafeRawPointer,UnsafeMutablePointer 未指定类型的指针结构体
1.2.3 UnsafeBufferPointer,UnsafeMubleBufferPointer,UnsafeMutableRawBufferPointer 定义一个范围的指针
1.3 常用操作
1.3.1 unsafePointer指向的内存转为其他类型 (withMemoryRebound)
var tom:Character = "a"
let int_tom = UnsafeMutablePointer(&tom).withMemoryRebound(to: UInt8.self, capacity: 1) {
return $0
}
int_tom.pointee = 97
1.3.2 类似c语言中的指针“+“ 操作 更多类似的操作可以看swift api文档
var m:UInt16 = 256
let p = UnsafeMutablePointer(&m).withMemoryRebound(to: UInt8.self, capacity: 2) {
return $0
}
p.pointee = 0;
(p + 1).pointee = 1;
1.3.2 对于unsafeRawPointer 类型的指针,可以使用bindMemory 或者 assumingMemoryBound 进行类型
var tom:Character = "a"
struct struct_char {
var chars:Character
}
let int_tom = UnsafeMutablePointer(&tom).withMemoryRebound(to: UInt8.self, capacity: 1) {
return $0
}
let int_tom2 = UnsafeMutableRawPointer(&tom).bindMemory(to: UInt8.self, capacity: 1)
let int_tom3 = UnsafeMutableRawPointer(&tom).assumingMemoryBound(to: struct_char.self)
if int_tom.pointee == int_tom2.pointee,tom == int_tom3.pointee.chars {
print("equal")
}
//控制台输出equal