UnsafeMutableRawPointer(variable)

时间:2018-10-11 05:26:55

标签: swift unsafemutablepointer

如果我想获取变量的unsafemutablerawpointer。 但是,如果没有创建副本或缓冲区,那么最佳/有效的方法是什么?

以下示例有效!

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

1 个答案:

答案 0 :(得分:0)

它不安全,如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规范中创建副本或缓冲区