klefevre
klefevre

Reputation: 8735

How to map an UnsafePointer to another type?

I'm trying to convert an UnsafePointer<UInt16> to an UnsafePointer<Float> and so far I ended 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 the feeling it's not an efficient way since I'm creating an intermediate Array... Is there a better way to do that ?

Upvotes: 3

Views: 162

Answers (1)

Rob
Rob

Reputation: 437432

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 that MemoryLayout<Float>.size is 4 (i.e. 32 bits) and MemoryLayout<UInt16> is obviously 2 (i.e.. 16 bits), so the bufferSize of your Float will be half of that of your UInt16 buffer.

Upvotes: 1

Related Questions