In Swift I want to write a struct as a binary file, my struct looks like this:
struct Bitmap {
var bfh: BitmapFileHeader
var bih: BitmapInfoHeader
var imageData: Data
}
the BitmapFileHeader and BitmapInfoHeader contain only UInt32 and UInt16 variables.
Now it should be quite easy to write it with this:
let data = withUnsafeBytes(of: myStruct) { Data($0) }
but the imageData won't be written because it's from type Data.
Ok, so I have to write it like this:
withUnsafeBytes(of: myBMP.bfh) { data.append(contentsOf: $0) }
withUnsafeBytes(of: myBMP.bih) { data.append(contentsOf: $0) }
data.append(myBMP.imageData)
But that inserts padding so that every variable uses 4 bytes instead of what I defined.
So I have to write each variable like this:
withUnsafeBytes(of: myBMP.bfh.type) { data.append(contentsOf: $0) }
withUnsafeBytes(of: myBMP.bfh.size) { data.append(contentsOf: $0) }
and so on...
Seriously? Is there really no easy generic way to just write the Data as is?
#swift #struct