Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnsafeMutablePointer Warning with Swift 5

I had this:

let alphaPtr = UnsafeMutablePointer<vImagePixelCount>(mutating: alpha) as UnsafeMutablePointer<vImagePixelCount>?

Which now I get the warning:

Initialization of 'UnsafeMutablePointer' (aka 'UnsafeMutablePointer') results in a dangling pointer

Detailed warning consists of:

  1. Implicit argument conversion from '[vImagePixelCount]' (aka 'Array') to 'UnsafePointer' (aka 'UnsafePointer') produces a pointer valid only for the duration of the call to 'init(mutating:)'

  2. Use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope

Is there a way around this?

like image 522
Gizmodo Avatar asked Mar 26 '20 14:03

Gizmodo


2 Answers

Try this

var bytes = [UInt8]()
let uint8Pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: bytes.count)
uint8Pointer.initialize(from: &bytes, count: bytes.count)
like image 72
Rajasekhar Pasupuleti Avatar answered Nov 15 '22 15:11

Rajasekhar Pasupuleti


It was never safe to do this, and the compiler now is warning you more aggressively.

let alphaPtr = UnsafeMutablePointer ...

At the end of this line, alphaPtr is already invalid. There is no promise that what it points to is still allocated memory.

Instead, you need to nest whatever usage you need into a withUnsafeMutablePointer() (or withUnsafePointer()) block. If you cannot nest it into a block (for example, if you were storing the pointer or returning it), there is no way to make that correct. You'll have to redesign your data management to not require that.

like image 7
Rob Napier Avatar answered Nov 15 '22 14:11

Rob Napier