200522--swift语法之UnsafeMutableRawPointer结构体

本文深入探讨Swift中的`UnsafeMutableRawPointer`结构体,包括其内存管理、原始和类型化内存、指针算术及隐式转换。了解如何使用此类型访问和操作非类型化数据,同时注意内存生命周期的管理,以避免潜在问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

     --UnsafeMutableRawPointer类型不提供自动内存管理、类型安全性和对齐保证。您要负责处理 使用不安全指针时的 内存的生命周期,以避免内存泄漏或产生未定义的行为。

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.

       --您手动管理的内存可以是非类型化的,也可以绑定到特定的类型。您可以使用UnsafeMutableRawPointer类型来访问和管理内存中的原始字节,无论该内存是否已绑定到特定类型。

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.

            --UnsafeMutableRawPointer实例引用的内存可以处于以下几种状态之一。许多指针操作 必须只限于 具有特定状态的内存 的指针,您必须跟踪正在处理的内存的状态,并了解不同操作对内存状态的修改。内存可以是未被类型化和未被初始化的,因此可以将内存绑定到类型但不进行初始化,也可以绑定到类型并初始化到值。最后,以前分配的内存可能已经被释放,但是却留下了 引用未分配内存的 指针

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.

           可以使用initializeMemory(as:from:)moveInitializeMemory(as:from:count:)方法将原始内存绑定到一个类型,并用一个或一系列值初始化它。要将未初始化的内存绑定到类型而不初始化它,请使用bindMemory(To:count:)方法。这些方法都返回类型化指针,以便对内存进行进一步的类型化访问。

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.

       --被绑定到一个类型的内存,无论是初始化的还是未初始化的,通常使用UnsafePointer和UnsafeMutablePointer的类型化指针对象来访问。初始化、赋值和去初始化可以使用UnsafeMutablePointer方法来执行。

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.

        --已绑定到类型的内存只有在去初始化或绑定类型为trivial类型才能被重新绑定到其他类型。去初始化已经类型化的内存不会解除该内存类型的绑定。去初始化的内存可以使用相同类型的值、绑定到新类型或释放的值重新初始化。

Note

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.

      --一个平凡的类型的内存可以逐位复制,而无需进行间接寻址引用计数操作。通常,不包含强引用弱引用或其他形式间接寻址的本地Swift类型就是平凡类型trivial,导入的C结构和枚举也是如此。

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.

         --当内存绑定到某个类型时,当你以原始字节的形式从内存读取或写入该内存时,必须确保满足所有的对齐要求。而只有当绑定类型为trivial平凡类型时,才必须将其作为原始字节写入类型化内存。

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:

        --带有原始指针的指针运算是在字节级执行的。当您对原始指针进行加减操作时,结果是一个新的原始指针被该字节数偏移。下面的示例分配了4个字节的内存,并将0xFF存储在所有4个字节中:

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.

        --上面的代码将值0xFFFF_FFFF存储到新分配的四个字节中,然后加载第一个字节作为UInt8实例,加载第三个和第四个字节作为UInt16实例。

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.

      --当调用的函数或方法使用UnsafeMutableRawPointer作为参数时,你可以传递该指针特定类型的实例、也可以传递兼容指针类型的实例,或者使用Swift的隐式桥接传递兼容指针。

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

       --例如,以下代码示例中的print(address:as:)函数将UnsafeMutableRawPointer的实例作为它的第一个参数

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.

         --与Swift中典型的做法一样,可以使用UnsafeMutableRawPointer实例调用print(address: As:)函数。这个例子将rawPointer作为初始参数传递。

// '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.

       --因为类型化指针在作为参数传递时可以隐式转换为原始指针,所以你还可以使用 任何可变类型化指针的 实例来调用print(address:as:)。

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:):

       --或者,可以使用Swift的隐式桥接将指针传递到实例或数组的元素。使用inout语法隐式地创建指向任何类型实例的指针。下面的示例使用隐式桥接在调用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:).

         --当使用inout语法传递数组时,会隐式地创建一个指向数组元素的可变指针。本例使用隐式桥接在调用print(address:as:)时传递一个指向numbers数组元素的指针(类型化的但未初始化的指针)

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

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 UnsafeMutableRawPointer initializer.

       --通过隐式桥接实例或数组元素创建的指针仅在被调用的函数执行期间有效。在函数执行后转义要使用的指针是未定义的行为。特别是,在调用UnsafeMutableRawPointer初始化器时,不要使用隐式桥接

var number = 5
let numberPointer = UnsafeMutableRawPointer(&number)
// Accessing 'numberPointer' is undefined behavior.

Topics         --专题

Type Aliases              --类型别名

typealias UnsafeMutableRawPointer.Pointee

 

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.

       --从一个AutoreleasingUnsafeMutablePointer实例创建一个新的原始指针。

 

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.

           --从一个AutoreleasingUnsafeMutablePointer实例创建一个新的原始指针。

 

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 customPlaygroundQuickLook: _PlaygroundQuickLook

A custom playground Quick Look for this instance.

Deprecated       --已丢弃

 

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 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 storeBytes<T>(of: T, toByteOffset: Int, as: T.Type)

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

 

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 + (Int, UnsafeMutableRawPointer) -> UnsafeMutableRawPointer

static func + (UnsafeMutableRawPointer, Int) -> UnsafeMutableRawPointer

static func += (inout UnsafeMutableRawPointer, Int)

static func - (UnsafeMutableRawPointer, Int) -> UnsafeMutableRawPointer

static func - (UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Int

static func -= (inout UnsafeMutableRawPointer, Int)

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, UnsafeMutableRawPointer) -> ClosedRange<UnsafeMutableRawPointer>

Returns a closed range that contains both of its bounds.

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 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 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

Strideable

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值