iosswiftswift3swift5unsafemutablepointer

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


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.


Solution

  • 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.