如何从UnsafeMutableRawPointer中获取字节? [英] How to get bytes out of an UnsafeMutableRawPointer?

查看:503
本文介绍了如何从UnsafeMutableRawPointer中获取字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将UnsafeMutableRawPointer(Swift 3中的新增功能)指向的一个访问字节(或Int16,float等)从内存中移出,然后由C API(核心音频等)传递给Swift函数

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 Audio, etc.)

推荐答案

load<T>从内存中读取原始字节,并构造一个T类型的值:

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

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

(可选)以字节偏移:

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

还有assumingMemoryBound(),它可以将Unsafe[Mutable]RawPointer转换为Unsafe[Mutable]Pointer<T>,假设指向的存储器包含类型T的值:

There is also assumingMemoryBound() which converts from a Unsafe[Mutable]RawPointer to a Unsafe[Mutable]Pointer<T>, 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)

如@Hamish所说,有关更多信息和详细信息,请访问

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

这篇关于如何从UnsafeMutableRawPointer中获取字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆