Writing structure to output stream in Swift 3

I'm trying to stream a structure so that it can then be sent over a socket to another device. The code works, but the data is incorrect. And every time random data is sent - then I am doing something wrong. Where am I going wrong? Here is my code:

 public struct PStypes {
    var u: UInt32              //< [X_XXXXXX V]
    var i: UInt32              //< [X_XXXXXX A]
   }
 func sendMessage(message: String) {
    var task = PStypes(u: 7, i: 9)
    var bufferData = NSData(bytes: &task, length: 8)
    var data:Data = bufferData as Data
    var bufferDataSize = data.count                
    let bytesWritten = withUnsafePointer(to: &data) {
        $0.withMemoryRebound(to: UInt8.self, capacity: bufferDataSize) {
            outputStream.write($0, maxLength: bufferDataSize)
        }
    }   
}

      

+3


source to share


2 answers


The problem with this code:

let bytesWritten = withUnsafePointer(to: &data) {
    $0.withMemoryRebound(to: UInt8.self, capacity: bufferDataSize) {
        outputStream.write($0, maxLength: bufferDataSize)
    }
}

      

this results in pointing to the data structure Data

, not the data it stores. You can fix this using:



let bytesWritten = data.withUnsafeBytes {
    outputStream.write($0, maxLength: 8)
}

      

it also simplifies the code a bit!

+2


source


var task = PStypes (u: 7, i: 9)



I think you are passing Int value instead of UInt32

0


source







All Articles