“This is the 22nd day of my participation in the First Challenge 2022. For details: First Challenge 2022”

Memory binding

Three different apis are provided in Swift to bind/rebind Pointers:

  • assumingMemoryBound(to:)
  • bindMemory(to: capacity:)
  • withMemoryRebound(to: capacity: body:)

assumingMemoryBound

We define a method as follows:

func testPoint(_ p: UnsafePointer<Int>) {
    print(p)
}
Copy the code

If we want to use this method, we need to pass in a type pointer; But we only have native Pointers, so how do we do that? For example:

Since testPoint requires a pointer of type Int and our trailing closure has a pointer of type tuple, passing it directly will cause an error! The assumption MemoryBound is used for pointer binding:

  • First of all byUnsafeRawPointerwilltuplePtrConvert to aThe original pointer;
  • Then throughassumingMemoryBoundBind it toIntType;

The sumingMemoryBound can be used to tell the compiler that we are of the same type and that there is no need to check if we only have native Pointers or if we need to operate on two Pointers that are of the same type and we don’t want to have to run through a series of conversion operations.

The essence of the assumption Memorybound is to bypass the compiler and essentially do nothing;

bindMemory

BindMemory is used to bind current memory information; In the above code, we can achieve the same result by using bindMemory:

The difference between the assumption MemoryBound and the assumption MemoryBound is that the assumption memorybound bypases the compiler, whereas bindMemory converts types directly. UnsafePointer<(Int, Int)> to UnsafePointer

;

BindMemory is used to change the type of the current memory binding

withMemoryRebound

Let’s look at the following example code:

func testPoint(_ p: UnsafePointer<Int8>){}let Uint8Ptr = UnsafePointer<UInt8>.init(bitPattern: 10)
Copy the code

Uint8Ptr = Uint8Ptr = Uint8Ptr = Uint8Ptr = Int8

We can bind memory to int8.self with withMemoryRebound, which only works in the current scope.

WithMemoryRebound is the type used to temporarily change the current memory binding

The above three ways of memory binding are common in Swift. Flexible application in development will greatly reduce the complex conversion process of code.