JAL JAL - 2 years ago 76
Swift Question

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

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

doesn't exist in the language anymore, and initializing the pointer (
) is deprecated and just sets the pointer to

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<()>')

Answer Source

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

var somePointer: UnsafeMutablePointer<Void> = nil
withUnsafePointer(&somePointer) { somePointer = UnsafeMutablePointer($0) }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download