UnsafeMutableRawPointer(变量)有多安全

how safe is UnsafeMutableRawPointer( variable )

如果我想获取一个变量的unsafemutablerawpointer。 然而,在不创建副本或缓冲区的情况下,best/efficient 的方法是什么?

下面的例子有效!

var number:UInt = 5

let numberPointer = UnsafeMutableRawPointer(&number)

var pointer:UnsafeMutablePointer<UInt8> = numberPointer.bindMemory(to: UInt8.self, capacity: size)

pointer[0] = 88

print(numberPointer) // 88 

然而来自苹果的文档:

docs

不像 Apple 的文档或我的评论那样安全。

如果你想以某种安全的方式进行,你可能需要这样写:

var number: UInt = 5

let size = MemoryLayout.size(ofValue: number)
withUnsafeMutableBytes(of: &number) {numberUmbp in
    let numberPointer = numberUmbp.baseAddress!
    let pointer: UnsafeMutablePointer<UInt8> = numberPointer.bindMemory(to: UInt8.self, capacity: size)

    pointer[0] = 88
} //`pointer` (or `numberPointer`) is guaranteed to be valid only inside this closure

print(number) // 88

当然,指针pointer只在闭包内部有效

如果你想提取一些更稳定和永久的地址,你无法避免创建副本或缓冲区,在Swift的当前规范中。