UnsafeMutablePointer Warning with Swift 5

非 Y 不嫁゛ 提交于 2020-05-07 09:20:07

问题


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?


回答1:


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.




回答2:


Do you need use the withUnsafeBufferPointer method from Array as

var alphaPtr: UnsafeBufferPointer = alpha.withUnsafeBufferPointer { $0 }

that's command produce a pointer optional if you need working with a specific type could you you use bindMemory(to:) or other function that match with you requirements.

Sometimes use a &alpha if you need a UnsafeRawPointer as a function parameter.



来源:https://stackoverflow.com/questions/60869370/unsafemutablepointer-warning-with-swift-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!