'UnsafePointer<UInt8>' 的初始化导致悬空指针
Initialization of 'UnsafePointer<UInt8>' results in a dangling pointer
试图清除我的 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' 的初始化导致悬空指针
从“[UInt8]”到 'UnsafePointer' 的隐式参数转换产生一个指针,仅在调用 'init(_:)'
期间有效
在 Array 上使用 '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 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' 的初始化导致悬空指针
从“[UInt8]”到 'UnsafePointer' 的隐式参数转换产生一个指针,仅在调用 'init(_:)'
期间有效在 Array 上使用 '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)