변경하려는 메모리 타입이 확실할 때 사용
import Foundation
let headerAddr: UnsafeMutableRawPointer = 0x0000000103178000
// mach_header_64의 사이즈 만큼을 Addr에 더한다.
let newAddress = headerAddr + MemoryLayout<mach_header_64>.size
// segmentCmdPtr에 계산한 newAddress의 주소를 UnsafeMutablePointer<segment_command_64>형으로 바인딩한다.
let segmentCmdPtr = newAddress.assumingMemoryBound(to: segment_command_64.self)
메모리 포인터의 타입 변경 시 적절한 메모리를 부여할 때
일반적으로 assumingMemoryBound 와 비교하여 더 안정적이므로, pointer 유형 변경 시 bindeMemory를 사용할 것을 권고한다.
인자로 들어가는 capacity는 alloc 시 사용되는 capacity와는 의미가 다르다. 메모리가 할당되는게 아니라 안정성을 위해 사용되며 버퍼 오버플로우를 방지한다. 컴파일러에게 얼만큼의 메모리를 사용할지 알려주는 용도.
예를 들어 (to: Int.self, capacity: 1)은 메모리에 Int 유형을 하나 가지고 있다는 의미. 만약 해당 포인터가 Int 형을 10개 가지고 있다고 한다면, (to: Int.self, capacity: 10)으로 작성하면 된다.
let rawPtr: UnsafeMutableRawPointer = 0x0000000103178000
// rawPtr을 UnsafeMutablePointer<Int>형으로 리바인딩한다.
let typedPtr = rawPtr.bindMemory(to: Int.self, capacity: 1)
클로저 내에서 포인터 메모리를 일시적으로 다른 메모리로 변경하여 사용
let buffer = UnsafeMutablePointer<Int>.allocate(capacity: 1)
buffer.withMemoryRebound(to: UInt8.self, capacity: 1) { byteBuffer in
// 클로저 내에서 buffer 포인터를 byteBuffer에 UInt8 형으로 리바인딩하여 사용
}
// 클로저가 종료됐으므로 buffer 포인터는 Int로 다시 리바인딩 됨
buffer.deallocate()