0

I am trying to manually convert Swift 3 code to Swift 5, but am getting error when trying to cast memory.

 let buffer: UnsafePointer<Int16> init<T>(buffer: UnsafePointer<T>) { self.buffer = UnsafePointer<Int16>(buffer) } 

The error is forced typecast which new Swift version is not allowing.

 Cannot convert value of type 'UnsafePointer<T>' to expected argument type 'UnsafePointer<Int16>' 

I am not sure what is the right way to rebind memory to 'UnsafePointer<Int16>', forcibly.

1 Answer 1

2

The UnsafePointer reference page explains the correct, but tedious, procedure:

When you need to permanently rebind memory to a different type, first obtain a raw pointer to the memory and then call the bindMemory(to:capacity:) method on the raw pointer. The following example binds the memory referenced by uint8Pointer to one instance of the UInt64 type:

let uint64Pointer = UnsafeRawPointer(uint8Pointer) .bindMemory(to: UInt64.self, capacity: 1) 

You're supposed to tell the compiler how much memory you're rebinding (using the capacity parameter) because it may have already copied some of that memory to registers or the stack and it needs to know you're invalidating those copies.

Sign up to request clarification or add additional context in comments.

2 Comments

I modified the line as self.buffer = UnsafeRawPointer(buffer).bindMemory(to: T.self, capacity: length)....but still get the same error
It should be .bindMemory(to: UInt16.self, capacity: someNumberOfUInt16s) because you want to create an UnsafePointer<UInt16>.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.