Search code examples
swiftswift-extensions

Converation from array of Bytes to Struct. Swift


I have dump of bytes and i need to parse structures

c++ exmpl:

(*(SomeStruct*)(bufPtr))

how can i do it on swift?


Solution

  • The equivalent of your C code would be:

    let s = UnsafePointer<SomeStruct>(bufPtr).memory
    

    (assuming bufPtr is of a type that UnsafePointer has an unnamed-argument initializer for - if not you may need another specific initializer, or to do a bit more coercion.)

    Same caveats that would apply in C/C++ apply here i.e. if it turns out bufPtr doesn’t point to a SomeStruct, you’ll be sorry.

    If on the other hand you want to step through the bytes one by one, you could create an var ptr = UnsafePointer<UInt8>(bufPtr), which can be indexed and incremented like a C pointer (i.e. ptr[i] and ++ptr).

    If you know in advance how many bytes you’ve read, you can also stick it in a buffer (let buf = UnsafeBufferPointer(start: ptr, count: i)) which lets you treat it like a regular collection (use with for-in, map, find etc). Again, the key is in the name – this is unsafe if you screw up the count.