Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.

2015-12-10

How to create an Unsafe(Mutable)Pointer

Swift is rather restrictive in the creation of pointers. But when we do low level programming it is sometimes necessary to use pointers. Especially when interfacing to the C-APIs of the underlying Unix system.

The "&" is used in arguments to create a pointer. But cannot be used in other places for the same purpose.

So how to create a pointer outside of a function argument?

Well, Apple has provided us with the withUnsafeMutablePointer and withUnsafePointer functions to deal with this. They take a few arguments and a closure. The argument is converted into a pointer that can subsequently be used inside the closure.

An example:

        var telemetry = Telemetry()
        let result = withUnsafeMutablePointer(&telemetry, {
            ptr in
            // From here on 'ptr' is a UnsafeMutablePointer<Telemetry>
            ...
        })

The same can be done for UnsafePointer as well.
And there are variations on withUnsafeMutablePointer and withUnsafePointer that allow for multiple pointers to be created at once.
The result is the result returned from the closure, which is neat too. In fact the conversion functions are defined as this:

public func withUnsafeMutablePointer<T, Result>(inout arg: T, @noescape _ body: UnsafeMutablePointer<T> throws -> Result) rethrows -> Result

Hence they do not only return the result from the closure, but they will even rethrow any execptions the closure might throw.

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment