gpt4 book ai didi

xcode - Swift 3使用 'withUnsafeBufferPointer'从网络套接字读取- 'init'无法使用 'withMemoryRebound'

转载 作者:行者123 更新时间:2023-12-03 11:59:46 25 4
gpt4 key购买 nike

我在Swift 2.3中有一个从网络套接字读取Int值的函数

open func readInt() -> Int32 {
var intValueBuffer = [UInt8](repeating: 0, count: MemoryLayout<Int32>.size)
self.stream!.read (&intValueBuffer, maxLength: MemoryLayout<Int32>.size)
let intValue = intValueBuffer.withUnsafeBufferPointer({
UnsafePointer<Int32>($0.baseAddress!).pointee
})
return Int32(bigEndian: intValue)
}

迁移到Swift 3之后,我遇到了这个错误。我还无法弄清楚实际需要更改的内容,我们将不胜感激

enter image description here

最佳答案

UInt8指针到Int32指针的转换
必须使用withMemoryRebound()明确指定:

func readInt() -> Int32 {
var intValueBuffer = [UInt8](repeating: 0, count: MemoryLayout<Int32>.size)
self.stream!.read(&intValueBuffer, maxLength: MemoryLayout<Int32>.size)
let intValue = intValueBuffer.withUnsafeBufferPointer({
$0.baseAddress!.withMemoryRebound(to: Int32.self, capacity: 1) {
$0.pointee
}
})
return Int32(bigEndian: intValue)
}

或者,读入 Data对象而不是数组:
func readInt() -> Int32 {
var intValueBuffer = Data(count: MemoryLayout<Int32>.size)
intValueBuffer.withUnsafeMutableBytes {
_ = self.stream!.read($0, maxLength: MemoryLayout<Int32>.size)
}
return Int32(bigEndian: intValueBuffer.withUnsafeBytes { $0.pointee })
}

或直接转换为整数变量:
func readInt() -> Int32 {
var intValue: Int32 = 0
withUnsafePointer(to: &intValue) {
$0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<Int32>.size) {
_ = self.stream!.read($0, maxLength: MemoryLayout<Int32>.size)
}
}
return Int32(bigEndian: intValue)
}

有关更多信息,请参见swift.org上的 UnsafeRawPointer Migration

您可能还需要检查 read方法的返回值
这是实际读取的字节数;如果读取操作失败,则为-1。

关于xcode - Swift 3使用 'withUnsafeBufferPointer'从网络套接字读取- 'init'无法使用 'withMemoryRebound',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39964712/

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