How to get bytes out of an UnsafeMutableRawPointer?

后端 未结 4 1161
孤独总比滥情好
孤独总比滥情好 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:39

    Here are the api documentation of Unsafe[Mutable]RawPointer to T/Unsafe[MutablePointer] conversion:

    /// Binds the allocated memory to type `T` and returns an
    /// `UnsafePointer` to the bound memory at `self`.
    ///
    /// - Precondition: The memory is uninitialized.
    /// - Postcondition: The memory is bound to 'T' starting at `self` continuing
    ///   through `self` + `count` * `MemoryLayout.stride`
    /// - Warning: Binding memory to a type is potentially undefined if the
    ///   memory is ever accessed as an unrelated type.
    public func bindMemory(to type: T.Type, capacity count: Int) -> UnsafePointer
    
    /// Converts from an `UnsafeRawPointer` to UnsafePointer given that
    /// the region of memory starting at `self` is already bound to type `T`.
    ///
    /// - Precondition: The memory is bound to 'T' starting at `self` for some
    ///   unspecified capacity.
    ///
    /// - Warning: Accessing memory via the returned pointer is undefined if the
    ///   if the memory has not been bound to `T`.
    public func assumingMemoryBound(to: T.Type) -> UnsafePointer
    
    /// Reads raw bytes from memory at `self + offset` and constructs a
    /// value of type `T`.
    ///
    /// - Precondition: The underlying pointer plus `offset` is properly
    ///   aligned for accessing `T`.
    ///
    /// - Precondition: The memory is initialized to a value of some type, `U`,
    ///   such that `T` is layout compatible with `U`.
    public func load(fromByteOffset offset: Int = default, as type: T.Type) -> T
    

    and then from Unsafe[MutablePointer] toT can be converted with pointee and move apis

    /// Accesses the `Pointee` instance referenced by `self`.
    ///
    /// - Precondition: the pointee has been initialized with an instance of
    ///   type `Pointee`.
    public var pointee: Pointee { get }
    
    /// Retrieves the `pointee`, returning the referenced memory to an
    /// uninitialized state.
    ///
    /// Equivalent to `{ defer { deinitialize() }; return pointee }()`, but
    /// more efficient.
    ///
    /// - Precondition: The pointee is initialized.
    ///
    /// - Postcondition: The memory is uninitialized.
    public func move() -> Pointee
    

提交回复
热议问题