Structure

UnsafeMutableRawPointer

A raw pointer for accessing and manipulating untyped data.

Declaration

@frozen struct UnsafeMutableRawPointer

Overview

The UnsafeMutableRawPointer type provides no automated memory management, no type safety, and no alignment guarantees. You are responsible for handling the life cycle of any memory you work with through unsafe pointers, to avoid leaks or undefined behavior.

Memory that you manually manage can be either untyped or bound to a specific type. You use the UnsafeMutableRawPointer type to access and manage raw bytes in memory, whether or not that memory has been bound to a specific type.

Understanding a Pointer’s Memory State

The memory referenced by an UnsafeMutableRawPointer instance can be in one of several states. Many pointer operations must only be applied to pointers with memory in a specific state—you must keep track of the state of the memory you are working with and understand the changes to that state that different operations perform. Memory can be untyped and uninitialized, bound to a type and uninitialized, or bound to a type and initialized to a value. Finally, memory that was allocated previously may have been deallocated, leaving existing pointers referencing unallocated memory.

Raw, Uninitialized Memory

Raw memory that has just been allocated is in an uninitialized, untyped state. Uninitialized memory must be initialized with values of a type before it can be used with any typed operations.

You can use methods like initializeMemory(as:from:) and moveInitializeMemory(as:from:count:) to bind raw memory to a type and initialize it with a value or series of values. To bind uninitialized memory to a type without initializing it, use the bindMemory(to:count:) method. These methods all return typed pointers for further typed access to the memory.

Typed Memory

Memory that has been bound to a type, whether it is initialized or uninitialized, is typically accessed using typed pointers—instances of UnsafePointer and UnsafeMutablePointer. Initialization, assignment, and deinitialization can be performed using UnsafeMutablePointer methods.

Memory that has been bound to a type can be rebound to a different type only after it has been deinitialized or if the bound type is a trivial type. Deinitializing typed memory does not unbind that memory’s type. The deinitialized memory can be reinitialized with values of the same type, bound to a new type, or deallocated.

When reading from or writing to memory as raw bytes when that memory is bound to a type, you must ensure that you satisfy any alignment requirements. Writing to typed memory as raw bytes must only be performed when the bound type is a trivial type.

Raw Pointer Arithmetic

Pointer arithmetic with raw pointers is performed at the byte level. When you add to or subtract from a raw pointer, the result is a new raw pointer offset by that number of bytes. The following example allocates four bytes of memory and stores 0xFF in all four bytes:

let bytesPointer = UnsafeMutableRawPointer.allocate(byteCount: 4, alignment: 1)
bytesPointer.storeBytes(of: 0xFFFF_FFFF, as: UInt32.self)

// Load a value from the memory referenced by 'bytesPointer'
let x = bytesPointer.load(as: UInt8.self)       // 255

// Load a value from the last two allocated bytes
let offsetPointer = bytesPointer + 2
let y = offsetPointer.load(as: UInt16.self)     // 65535

The code above stores the value 0xFFFF_FFFF into the four newly allocated bytes, and then loads the first byte as a UInt8 instance and the third and fourth bytes as a UInt16 instance.

Always remember to deallocate any memory that you allocate yourself.

bytesPointer.deallocate()

Implicit Casting and Bridging

When calling a function or method with an UnsafeMutableRawPointer parameter, you can pass an instance of that specific pointer type, pass an instance of a compatible pointer type, or use Swift’s implicit bridging to pass a compatible pointer.

For example, the print(address:as:) function in the following code sample takes an UnsafeMutableRawPointer instance as its first parameter:

func print<T>(address p: UnsafeMutableRawPointer, as type: T.Type) {
    let value = p.load(as: type)
    print(value)
}

As is typical in Swift, you can call the print(address:as:) function with an UnsafeMutableRawPointer instance. This example passes rawPointer as the initial parameter.

// 'rawPointer' points to memory initialized with `Int` values.
let rawPointer: UnsafeMutableRawPointer = ...
print(address: rawPointer, as: Int.self)
// Prints "42"

Because typed pointers can be implicitly cast to raw pointers when passed as a parameter, you can also call print(address:as:) with any mutable typed pointer instance.

let intPointer: UnsafeMutablePointer<Int> = ...
print(address: intPointer, as: Int.self)
// Prints "42"

Alternatively, you can use Swift’s implicit bridging to pass a pointer to an instance or to the elements of an array. Use inout syntax to implicitly create a pointer to an instance of any type. The following example uses implicit bridging to pass a pointer to value when calling print(address:as:):

var value: Int = 23
print(address: &value, as: Int.self)
// Prints "23"

A mutable pointer to the elements of an array is implicitly created when you pass the array using inout syntax. This example uses implicit bridging to pass a pointer to the elements of numbers when calling print(address:as:).

var numbers = [5, 10, 15, 20]
print(address: &numbers, as: Int.self)
// Prints "5"

Topics

Type Aliases

typealias UnsafeMutableRawPointer.Stride

A type that represents the distance between two values.

Initializers

init?<T>(AutoreleasingUnsafeMutablePointer<T>?)

Creates a new raw pointer from an AutoreleasingUnsafeMutablePointer instance.

init?<T>(UnsafeMutablePointer<T>?)

Creates a new raw pointer from the given typed pointer.

init<T>(UnsafeMutablePointer<T>)

Creates a new raw pointer from the given typed pointer.

init<T>(AutoreleasingUnsafeMutablePointer<T>)

Creates a new raw pointer from an AutoreleasingUnsafeMutablePointer instance.

init(RawPointer)

Creates a new raw pointer from a builtin raw pointer.

init?(UnsafeMutableRawPointer?)

Creates a new pointer from the given pointer.

init?(OpaquePointer?)

Creates a new typed pointer from the given opaque pointer.

init(OpaquePointer)

Creates a new typed pointer from the given opaque pointer.

init(UnsafeMutableRawPointer)

Creates a new pointer from the given pointer.

init?(bitPattern: Int)

Creates a new pointer from the given address, specified as a bit pattern.

init?(bitPattern: UInt)

Creates a new pointer from the given address, specified as a bit pattern.

init?(mutating: UnsafeRawPointer?)

Creates a new mutable raw pointer from the given immutable raw pointer.

init(mutating: UnsafeRawPointer)

Creates a new mutable raw pointer from the given immutable raw pointer.

Instance Properties

var customMirror: Mirror

The custom mirror for this instance.

var customPlaygroundQuickLook: _PlaygroundQuickLook

A custom playground Quick Look for this instance.

Deprecated
var debugDescription: String

A textual representation of the pointer, suitable for debugging.

var hashValue: Int

The hash value.

Instance Methods

func advanced(by: Int) -> UnsafeMutableRawPointer

Returns a value that is offset the specified distance from this value.

func assumingMemoryBound<T>(to: T.Type) -> UnsafeMutablePointer<T>

Returns a typed pointer to the memory referenced by this pointer, assuming that the memory is already bound to the specified type.

func bindMemory<T>(to: T.Type, capacity: Int) -> UnsafeMutablePointer<T>

Binds the memory to the specified type and returns a typed pointer to the bound memory.

func copyMemory(from: UnsafeRawPointer, byteCount: Int)

Copies the specified number of bytes from the given raw pointer’s memory into this pointer’s memory.

func deallocate()

Deallocates the previously allocated memory block referenced by this pointer.

func distance(to: UnsafeMutableRawPointer) -> Int

Returns the distance from this pointer to the given pointer, counted as instances of the pointer’s Pointee type.

func hash(into: inout Hasher)

Hashes the essential components of this value by feeding them into the given hasher.

func initializeMemory<T>(as: T.Type, from: UnsafePointer<T>, count: Int) -> UnsafeMutablePointer<T>

Initializes the memory referenced by this pointer with the values starting at the given pointer, binds the memory to the values’ type, and returns a typed pointer to the initialized memory.

func initializeMemory<T>(as: T.Type, repeating: T, count: Int) -> UnsafeMutablePointer<T>

Initializes the memory referenced by this pointer with the given value, binds the memory to the value’s type, and returns a typed pointer to the initialized memory.

func load<T>(fromByteOffset: Int, as: T.Type) -> T

Returns a new instance of the given type, constructed from the raw memory at the specified offset.

func moveInitializeMemory<T>(as: T.Type, from: UnsafeMutablePointer<T>, count: Int) -> UnsafeMutablePointer<T>

Initializes the memory referenced by this pointer with the values starting at the given pointer, binds the memory to the values’ type, deinitializes the source memory, and returns a typed pointer to the newly initialized memory.

func predecessor() -> UnsafeMutableRawPointer

Returns a pointer to the previous consecutive instance.

func storeBytes<T>(of: T, toByteOffset: Int, as: T.Type)

Stores the given value’s bytes into raw memory at the specified offset.

func successor() -> UnsafeMutableRawPointer

Returns a pointer to the next consecutive instance.

Type Methods

static func allocate(byteCount: Int, alignment: Int) -> UnsafeMutableRawPointer

Allocates uninitialized memory with the specified size and alignment.

Operator Functions

static func != (UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Bool

Returns a Boolean value indicating whether two values are not equal.

static func ... (UnsafeMutableRawPointer) -> PartialRangeFrom<UnsafeMutableRawPointer>

Returns a partial range extending upward from a lower bound.

static func ... (UnsafeMutableRawPointer) -> PartialRangeThrough<UnsafeMutableRawPointer>

Returns a partial range up to, and including, its upper bound.

static func ..< (UnsafeMutableRawPointer) -> PartialRangeUpTo<UnsafeMutableRawPointer>

Returns a partial range up to, but not including, its upper bound.

static func ..< (UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Range<UnsafeMutableRawPointer>

Returns a half-open range that contains its lower bound but not its upper bound.

static func < (UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Bool

Returns a Boolean value indicating whether the value of the first argument is less than that of the second argument.

static func < (UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Bool

Returns a Boolean value indicating whether the first pointer references an earlier memory location than the second pointer.

static func <= (UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Bool

Returns a Boolean value indicating whether the value of the first argument is less than or equal to that of the second argument.

static func == (UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Bool

Returns a Boolean value indicating whether two values are equal.

static func == (UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Bool

Returns a Boolean value indicating whether two pointers are equal.

static func > (UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Bool

Returns a Boolean value indicating whether the value of the first argument is greater than that of the second argument.

static func >= (UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Bool

Returns a Boolean value indicating whether the value of the first argument is greater than or equal to that of the second argument.

Relationships

Conforms To

See Also

Raw Pointers

struct UnsafeRawPointer

A raw pointer for accessing untyped data.

struct UnsafeRawBufferPointer

A nonowning collection interface to the bytes in a region of memory.

struct UnsafeMutableRawBufferPointer

A mutable nonowning collection interface to the bytes in a region of memory.