How do I map UnsafePointer to another type?
I am trying to convert UnsafePointer<UInt16>
to UnsafePointer<Float>
and so far I ended up with this solution:
let bufferSize = 1024
let buffer: UnsafePointer<UInt16> = ....
let tmp = UnsafeBufferPointer(start: buffer, count: bufferSize).map(Float.init)
let converted: UnsafePointer<Float> = UnsafePointer(tmp)
It works, but I have a feeling that this is not an efficient way since I am creating an intermediate Array
... Is there a better way to do this?
source to share
You can use withMemoryRebound
to convert a pointer from one type to another:
buffer.withMemoryRebound(to: Float.self, capacity: 1024) { converted -> Void in
// use `converted` here
}
But be careful to MemoryLayout<Float>.size
be 4
(i.e. 32 bits) and MemoryLayout<UInt16>
obviously 2
(i.e. 16 bits), so bufferSize
yours Float
will be half of that buffer of yours UInt16
.
source to share