struct UnsafePointer<Pointee>
Inheritance |
CVarArg, Comparable, CustomDebugStringConvertible, CustomPlaygroundQuickLookable, CustomReflectable, Equatable, Hashable, Strideable
View Protocol Hierarchy →
|
---|---|
Associated Types | |
Import | import Swift |
Initializers
Creates a new typed pointer from the given opaque pointer.
from
: The opaque pointer to convert to a typed pointer.
Declaration
init(_ from: OpaquePointer)
Creates an immutable typed pointer referencing the same memory as the given mutable pointer.
other
: The pointer to convert.
Declaration
init(_ other: UnsafeMutablePointer<Pointee>)
Creates a new pointer from the given typed pointer.
other
: The typed pointer to convert.
Declaration
init(_ other: UnsafePointer<Pointee>)
Creates a new typed pointer from the given opaque pointer.
from
: The opaque pointer to convert to a typed pointer. If
from
is nil
, the result of this initializer is nil
.
Declaration
init?(_ from: OpaquePointer?)
Creates an immutable typed pointer referencing the same memory as the given mutable pointer.
other
: The pointer to convert. If other
is nil
, the
result is nil
.
Declaration
init?(_ other: UnsafeMutablePointer<Pointee>?)
Creates a new pointer from the given typed pointer.
other
: The typed pointer to convert. If other
is nil
, the
result is nil
.
Declaration
init?(_ other: UnsafePointer<Pointee>?)
Creates a new typed pointer from the given address, specified as a bit pattern.
The address passed as bitPattern
must have the correct alignment for
the pointer's Pointee
type. That is,
bitPattern % MemoryLayout<Pointee>.alignment
must be 0
.
bitPattern
: A bit pattern to use for the address of the new
pointer. If bitPattern
is zero, the result is nil
.
Declaration
init?(bitPattern: Int)
Creates a new typed pointer from the given address, specified as a bit pattern.
The address passed as bitPattern
must have the correct alignment for
the pointer's Pointee
type. That is,
bitPattern % MemoryLayout<Pointee>.alignment
must be 0
.
bitPattern
: A bit pattern to use for the address of the new
pointer. If bitPattern
is zero, the result is nil
.
Declaration
init?(bitPattern: UInt)
Instance Variables
The custom mirror for this instance.
If this type has value semantics, the mirror should be unaffected by subsequent mutations of the instance.
Declaration
var customMirror: Mirror { get }
A custom playground Quick Look for this instance.
If this type has value semantics, the PlaygroundQuickLook
instance
should be unaffected by subsequent mutations.
Deprecated: UnsafePointer.customPlaygroundQuickLook will be removed in a future Swift version.
Declaration
var customPlaygroundQuickLook: PlaygroundQuickLook { get }
A textual representation of the pointer, suitable for debugging.
Declaration
var debugDescription: String { get }
The pointer's hash value.
The hash value is not guaranteed to be stable across different invocations of the same program. Do not persist the hash value across program runs.
Declaration
var hashValue: Int { get }
Accesses the instance referenced by this pointer.
When reading from the pointee
property, the instance referenced by
this pointer must already be initialized.
Declaration
var pointee: Pointee { get }
Subscripts
Accesses the pointee at the specified offset from this pointer.
For a pointer p
, the memory at p + i
must be initialized.
i
: The offset from this pointer at which to access an
instance, measured in strides of the pointer's Pointee
type.
Declaration
subscript(i: Int) -> Pointee { get }
Instance Methods
Returns a pointer offset from this pointer by the specified number of instances.
With pointer p
and distance n
, the result of p.advanced(by: n)
is
equivalent to p + n
.
The resulting pointer must be within the bounds of the same allocation as this pointer.
n
: The number of strides of the pointer's Pointee
type to
offset this pointer. To access the stride, use
MemoryLayout<Pointee>.stride
. n
may be positive, negative, or
zero.
Returns: A pointer offset from this pointer by n
instances of the
Pointee
type.
Declaration
func advanced(by n: Int) -> UnsafePointer<Pointee>
Deallocates the memory block previously allocated at this pointer.
This pointer must be a pointer to the start of a previously allocated memory
block. The memory must not be initialized or Pointee
must be a trivial type.
Declaration
func deallocate()
Returns the distance from this pointer to the given pointer, counted as
instances of the pointer's Pointee
type.
With pointers p
and q
, the result of p.distance(to: q)
is
equivalent to q - p
.
Typed pointers are required to be properly aligned for their Pointee
type. Proper alignment ensures that the result of distance(to:)
accurately measures the distance between the two pointers, counted in
strides of Pointee
. To find the distance in bytes between two
pointers, convert them to UnsafeRawPointer
instances before calling
distance(to:)
.
end
: The pointer to calculate the distance to.
Returns: The distance from this pointer to end
, in strides of the
pointer's Pointee
type. To access the stride, use
MemoryLayout<Pointee>.stride
.
Declaration
func distance(to end: UnsafePointer<Pointee>) -> Int
Hashes the essential components of this value by feeding them into the given hasher.
hasher
: The hasher to use when combining the components
of this instance.
Declaration
func hash(into hasher: inout Hasher)
Returns a pointer to the previous consecutive instance.
The resulting pointer must be within the bounds of the same allocation as this pointer.
Returns: A pointer shifted backward from this pointer by
MemoryLayout<Pointee>.stride
bytes.
Declaration
func predecessor() -> UnsafePointer<Pointee>
Returns a pointer to the next consecutive instance.
The resulting pointer must be within the bounds of the same allocation as this pointer.
Returns: A pointer advanced from this pointer by
MemoryLayout<Pointee>.stride
bytes.
Declaration
func successor() -> UnsafePointer<Pointee>
Executes the given closure while temporarily binding the specified number of instances to the given type.
Use this method when you have a pointer to memory bound to one type and
you need to access that memory as instances of another type. Accessing
memory as type T
requires that the memory be bound to that type. A
memory location may only be bound to one type at a time, so accessing
the same memory as an unrelated type without first rebinding the memory
is undefined.
The region of memory starting at this pointer and covering count
instances of the pointer's Pointee
type must be initialized.
The following example temporarily rebinds the memory of a UInt64
pointer to Int64
, then accesses a property on the signed integer.
let uint64Pointer: UnsafePointer<UInt64> = fetchValue()
let isNegative = uint64Pointer.withMemoryRebound(to: Int64.self) { ptr in
return ptr.pointee < 0
}
Because this pointer's memory is no longer bound to its Pointee
type
while the body
closure executes, do not access memory using the
original pointer from within body
. Instead, use the body
closure's
pointer argument to access the values in memory as instances of type
T
.
After executing body
, this method rebinds memory back to the original
Pointee
type.
Note: Only use this method to rebind the pointer's memory to a type
with the same size and stride as the currently bound Pointee
type.
To bind a region of memory to a type that is a different size, convert
the pointer to a raw pointer and use the bindMemory(to:capacity:)
method.
Parameters:
type: The type to temporarily bind the memory referenced by this
pointer. The type T
must be the same size and be layout compatible
with the pointer's Pointee
type.
count: The number of instances of T
to bind to type
.
body: A closure that takes a typed pointer to the
same memory as this pointer, only bound to type T
. The closure's
pointer argument is valid only for the duration of the closure's
execution. If body
has a return value, that value is also used as
the return value for the withMemoryRebound(to:capacity:_:)
method.
Returns: The return value, if any, of the body
closure parameter.
Declaration
func withMemoryRebound<T, Result>(to type: T.Type, capacity count: Int, _ body: (UnsafePointer<T>) throws -> Result) rethrows -> Result
Conditionally Inherited Items
The initializers, methods, and properties listed below may be available on this type under certain conditions (such as methods that are available on Array
when its elements are Equatable
) or may not ever be available if that determination is beyond SwiftDoc.org's capabilities. Please open an issue on GitHub if you see something out of place!
Where Stride : SignedInteger
Returns a countable closed range that contains both of its bounds.
Use the closed range operator (...
) to create a closed range of any type
that conforms to the Strideable
protocol with an associated signed
integer Stride
type, such as any of the standard library's integer
types. This example creates a ClosedRange<Int>
from zero up to,
and including, nine.
let singleDigits = 0...9
print(singleDigits.contains(9))
// Prints "true"
You can use sequence or collection methods on the singleDigits
range.
print(singleDigits.count)
// Prints "10"
print(singleDigits.last)
// Prints "9"
Parameters:)`. minimum: The lower bound for the range. maximum: The upper bound for the range.
Declaration
func ...(minimum: UnsafePointer<Pointee>, maximum: UnsafePointer<Pointee>) -> ClosedRange<UnsafePointer<Pointee>>
Declared In
Strideable
A pointer for accessing data of a specific type.
You use instances of the
UnsafePointer
type to access data of a specific type in memory. The type of data that a pointer can access is the pointer'sPointee
type.UnsafePointer
provides no automated memory management or 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
UnsafePointer
type to access and manage memory that has been bound to a specific type.Understanding a Pointer's Memory State
The memory referenced by an
UnsafePointer
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.Uninitialized Memory
Memory that has just been allocated through a typed pointer or has been deinitialized is in an uninitialized state. Uninitialized memory must be initialized before it can be accessed for reading.
Initialized Memory
Initialized memory has a value that can be read using a pointer's
pointee
property or through subscript notation. In the following example,ptr
is a pointer to memory initialized with a value of23
:Accessing a Pointer's Memory as a Different Type
When you access memory through an
UnsafePointer
instance, thePointee
type must be consistent with the bound type of the memory. If you do need to access memory that is bound to one type as a different type, Swift's pointer types provide type-safe ways to temporarily or permanently change the bound type of the memory, or to load typed instances directly from raw memory.An
UnsafePointer<UInt8>
instance allocated with eight bytes of memory,uint8Pointer
, will be used for the examples below.When you only need to temporarily access a pointer's memory as a different type, use the
withMemoryRebound(to:capacity:)
method. For example, you can use this method to call an API that expects a pointer to a different type that is layout compatible with your pointer'sPointee
. The following code temporarily rebinds the memory thatuint8Pointer
references fromUInt8
toInt8
to call the imported Cstrlen
function.When you need to permanently rebind memory to a different type, first obtain a raw pointer to the memory and then call the
bindMemory(to:capacity:)
method on the raw pointer. The following example binds the memory referenced byuint8Pointer
to one instance of theUInt64
type:After rebinding the memory referenced by
uint8Pointer
toUInt64
, accessing that pointer's referenced memory as aUInt8
instance is undefined.Alternatively, you can access the same memory as a different type without rebinding through untyped memory access, so long as the bound type and the destination type are trivial types. Convert your pointer to an
UnsafeRawPointer
instance and then use the raw pointer'sload(fromByteOffset:as:)
method to read values.Performing Typed Pointer Arithmetic
Pointer arithmetic with a typed pointer is counted in strides of the pointer's
Pointee
type. When you add to or subtract from anUnsafePointer
instance, the result is a new pointer of the same type, offset by that number of instances of thePointee
type.You can also use subscript notation to access the value in memory at a specific offset.
Implicit Casting and Bridging
When calling a function or method with an
UnsafePointer
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
printInt(atAddress:)
function in the following code sample expects anUnsafePointer<Int>
instance as its first parameter:As is typical in Swift, you can call the
printInt(atAddress:)
function with anUnsafePointer
instance. This example passesintPointer
, a pointer to anInt
value, toprint(address:)
.Because a mutable typed pointer can be implicitly cast to an immutable pointer with the same
Pointee
type when passed as a parameter, you can also callprintInt(atAddress:)
with anUnsafeMutablePointer
instance.Alternatively, you can use Swift's implicit bridging to pass a pointer to an instance or to the elements of an array. The following example passes a pointer to the
value
variable by using inout syntax:An immutable pointer to the elements of an array is implicitly created when you pass the array as an argument. This example uses implicit bridging to pass a pointer to the elements of
numbers
when callingprintInt(atAddress:)
.You can also use inout syntax to pass a mutable pointer to the elements of an array. Because
printInt(atAddress:)
requires an immutable pointer, although this is syntactically valid, it isn't necessary.No matter which way you call
printInt(atAddress:)
, Swift's type safety guarantees that you can only pass a pointer to the type required by the function---in this case, a pointer to anInt
.Important: The pointer created through implicit bridging of an instance or of an array's elements is only valid during the execution of the called function. Escaping the pointer to use after the execution of the function is undefined behavior. In particular, do not use implicit bridging when calling an
UnsafePointer
initializer.