gpt4 book ai didi

swift - 'UnsafePointer' 的初始化导致悬空指针

转载 作者:行者123 更新时间:2023-12-05 01:35:49 24 4
gpt4 key购买 nike

尝试清除我的 SWIFT 5/XCODE 项目中的一些警告,但我陷入了困境:

 let sendBytes:[UInt8] = [0x0, 0x0, 0x5, 0x0]
let msgData = Data(bytes: UnsafePointer<UInt8>(sendBytes), count: sendBytes.count)
socket.write(msgData, withTimeout: -1.0, tag: 0)
socket.readData(withTimeout: -1.0, tag: 0)

对于“UnsafePointer”,我收到以下警告和两条建议:

“UnsafePointer”的初始化导致悬空指针

  1. 从“[UInt8]”到“UnsafePointer”的隐式参数转换生成的指针仅在调用“init(_:)”期间有效

  2. 在数组上使用“withUnsafeBufferPointer”方法,以便将参数显式转换为对定义范围有效的缓冲区指针

这是我的解决方案,更好吗?

版本 1:

let sendBytes:[UInt8] = [0x0, 0x0, 0x5, 0x0]
let uint8Pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: sendBytes.count)
uint8Pointer.initialize(from: sendBytes, count: sendBytes.count)
let msgData = Data(bytes: uint8Pointer, count: sendBytes.count)
socket.write(msgData, withTimeout: -1.0, tag: 0)
socket.readData(withTimeout: -1.0, tag: 0)

版本 2:

let sendBytes:[UInt8] = [0x0, 0x0, 0x5, 0x0]                     
let uint8Pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: sendBytes.count)
uint8Pointer.initialize(from: sendBytes, count: sendBytes.count)
let msgData = Data(bytes: uint8Pointer, count: sendBytes.count)
socket.write(msgData, withTimeout: -1.0, tag: 0)
socket.readData(withTimeout: -1.0, tag: 0)
uint8Pointer.deallocate()

最佳答案

自 Swift 3 起,可以简单地使用 UInt8 数组初始化 Data 实例。

let sendBytes:[UInt8] = [0x0, 0x0, 0x5, 0x0]
let msgData = Data(sendBytes)

关于swift - 'UnsafePointer<UInt8>' 的初始化导致悬空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62618048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com