Home swift-unsaferawpointer
Post
Cancel

swift-unsaferawpointer

UnsafeRawPointer

@frozon struct UnsafeRawPointer

A raw pointer for accessing untyped data.

memory state

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.

To bind uninitialized memory to a type without initializing it, use the bindMemory(to:count:) method. This method returns a typed pointer 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.

1
2
3
A trivial type can be copied bit for bit with no indirection or reference-counting operations. Generally, native Swift types that do not contain strong or weak references or other forms of indirection are trivial, as are imported C structs and enumerations.

When reading from memory as raw bytes when that memory is bound to a type, you must ensure that you satisfy any alignment requirements.

Raw Pointer Arithmetic

1
2
3
4
5
6
7
8
9
10
11
12
let bytesPointer = UnsafeMutableRawPointer.allocate(byteCount: 4, alignment: 4)
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

// deallocate
bytesPointer.deallocate()
This post is licensed under CC BY 4.0 by the author.