Swift 5发出UnsafeMutablePointer警告 [英] UnsafeMutablePointer Warning with Swift 5

查看:947
本文介绍了Swift 5发出UnsafeMutablePointer警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

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

现在我得到警告:

'UnsafeMutablePointer'(又名)的初始化 'UnsafeMutablePointer')导致指针悬空

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

详细警告包括:

  1. 从'[vImagePixelCount]'(aka'Array')到'UnsafePointer'(aka的隐式参数转换) 'UnsafePointer')产生一个仅在持续时间内有效的指针 'init(mutating :)'的调用

  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:)'

对数组使用'withUnsafeBufferPointer'方法,以便将参数显式转换为对已定义有效的缓冲区指针 范围

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?

推荐答案

这样做从来都不是安全的,编译器现在会更积极地警告您.

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

let alphaPtr = UnsafeMutablePointer ...

在此行的末尾,alphaPtr已经无效.无法保证它所指向的仍然是已分配的内存.

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

相反,您需要将所需的任何用法嵌套到withUnsafeMutablePointer()(或withUnsafePointer())块中.如果您不能将其嵌套在一个块中(例如,如果您正在存储指针或将其返回),则没有办法使它正确.您必须重新设计数据管理,以免不必要.

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.

这篇关于Swift 5发出UnsafeMutablePointer警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆