Generic Structure
UnsafePointer
A pointer for accessing data of a specific type.
--用于访问特定类型数据的指针。
Declaration --声明
@frozen struct UnsafePointer<Pointee>
Overview --概览
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’s Pointee
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.
--您可以使用UnsafePointer类型的实例来访问内存中特定类型的数据。指针可以访问的数据类型是指针的指针类型。UnsafePointer不提供自动内存管理或对齐的保证。您要负责通过不安全的指针处理任何内存的生命周期,以避免泄漏或未定义的行为。
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.
--您手动管理的内存可以是非类型化的,也可以绑定到特定的类型。您可以使用UnsafePointer类型来访问和管理绑定到特定类型的内存。
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.
--UnsafePointer实例引用的内存可以处于几种状态之一。许多指针的操作 只能被应用在 具有 特定状态的内存的指针,您必须跟踪正在处理的内存的状态,并了解不同操作对该状态的修改。内存可以是未类型化和未初始化的,可以绑定到类型并未初始化,也可以绑定到类型并初始化到值。最后,以前分配的内存有可能已经被释放,且留下了 引用未分配内存的 现有指针。
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 of 23
:
--初始化的内存有一个值,该值可以使用指针的 指向单元属性 或通过 下标符号 读取。在下面的例子中,ptr是一个指向初始化值为23的内存的指针
let ptr: UnsafePointer<Int> = ...
// ptr.pointee == 23
// ptr[0] == 23
Accessing a Pointer’s Memory as a Different Type --变更指针类型来访问内存
When you access memory through an UnsafePointer
instance, the Pointee
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.
--当你通过一个UnsafePointer实例访问内存时,指针类型必须