Search code examples
swiftunsafe-pointers

Point an UnsafeMutablePointer<Void> to itself


In C, it is valid to have a pointer point to the memory location allocated to the pointer:

static void * SomeContext = &SomeContext;

I have seen this used in Objective-C codebases with KVO by using this pointer as the context in observeValueForKeyPath:ofObject:change:context:.

Is it possible to point a pointer to the memory space allocated for that pointer in Swift, or manually allocate memory for the pointer? Trying to point the pointer to the memory value of itself during initialization causes an error (as expected):

var somePointer: UnsafeMutablePointer<Void> = &somePointer // Error: Variable used within its own initial value

CMutableVoidPointer doesn't exist in the language anymore, and initializing the pointer (UnsafeMutablePointer<Void>()) is deprecated and just sets the pointer to nil.

Maybe something like:

var ptr = malloc(sizeof(UnsafeMutablePointer<Void>))
ptr = &ptr // Error: error: cannot assign value of type 'inout UnsafeMutablePointer<Void>' (aka 'inout UnsafeMutablePointer<()>') to type 'UnsafeMutablePointer<Void>' (aka 'UnsafeMutablePointer<()>')

Solution

  • On Swift 3:

    var somePointer = UnsafeMutableRawPointer(bitPattern: 1)!
    somePointer = UnsafeMutableRawPointer(mutating: &somePointer)
    
    print(somePointer)
    print(somePointer.load(as: UnsafeMutableRawPointer.self))
    // Output of both should be the same.
    

    Swift 2:

    Use withUnsafePointer to obtain the pointer to a variable. Then assign that to itself.

    var somePointer: UnsafeMutablePointer<Void> = nil
    withUnsafePointer(&somePointer) { somePointer = UnsafeMutablePointer($0) }