Search code examples
swiftunsafemutablepointer

how safe is UnsafeMutableRawPointer( variable )


If i want to obtain the unsafemutablerawpointer of a variable. Yet without creating copies or buffer, what is the best/efficient way to do so?

The below example works!

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 

Yet from apple's docs:

docs


Solution

  • It is not safe as in Apple's doc or as in my comment.

    If you want to do it in some safe way, you may need to write something like this:

    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
    

    Of course, the pointer pointer is only valid inside the closure.

    If you want to extract some more stable and permanent address, you cannot avoid creating copies or buffer, in the current specification of Swift.