1

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<()>')
JAL
  • 41,701
  • 23
  • 172
  • 300
  • What're you trying to achieve exactly? – Alexander May 31 '16 at 20:14
  • @AMomchilov How would you write `static void * SomeContext = &SomeContext;` in Swift. This isn't part of larger problem, I'm just trying to understand how C pointers bridged to Swift work. – JAL May 31 '16 at 20:16
  • 1
    I should have known you answered a question like this, thanks @MartinR. – JAL May 31 '16 at 20:23

1 Answers1

3

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) }
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005