How to get bytes out of an UnsafeMutableRawPointer?

后端 未结 4 1127
孤独总比滥情好
孤独总比滥情好 2020-12-02 21:05

How does one access bytes (or Int16\'s, floats, etc.) out of memory pointed to by an UnsafeMutableRawPointer (new in Swift 3) handed to a Swift function by a C API (Core Aud

4条回答
  •  渐次进展
    2020-12-02 21:24

    load reads raw bytes from memory and constructs a value of type T:

    let ptr = ... // Unsafe[Mutable]RawPointer
    let i16 = ptr.load(as: UInt16.self)
    

    optionally at a byte offset:

    let i16 = ptr.load(fromByteOffset: 4, as: UInt16.self)
    

    There is also assumingMemoryBound() which converts from a Unsafe[Mutable]RawPointer to a Unsafe[Mutable]Pointer, assuming that the pointed-to memory contains a value of type T:

    let i16 = ptr.assumingMemoryBound(to: UInt16.self).pointee
    

    For an array of values you can create a "buffer pointer":

    let i16bufptr = UnsafeBufferPointer(start: ptr.assumingMemoryBound(to: UInt16.self), count: count)
    

    A buffer pointer might already be sufficient for your purpose, it is subscriptable and can be enumerated similarly to an array. If necessary, create an array from the buffer pointer:

    let i16array = Array(i16bufptr)
    

    As @Hamish said, more information and details can be found at

    • SE-0107 UnsafeRawPointer API

提交回复
热议问题