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

标签 xcode sockets swift3

我在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/

相关文章:

ios - UISegmentedControl 更改 ONE 段的字体

ios - 设置包根中没有 'Child Pane' 选项

ios - Xcode 5 到 Xcode 4 项目运行

node.js - 是否可以使用同一个端口启用 tcp、http 和 websocket?

c - 关于套接字 select() 崩溃

Java Socket 命令行参数

ios - 无法使用自定义 DelegateProxy 和协议(protocol)接收事件

swift - 在 Swift 3 中解包可选整数的正确方法

ios - 在动态框架中包含静态库的公共(public)头文件

iphone - Apple Mac-o-Linker (id) 错误