I have dump of bytes and i need to parse structures
c++ exmpl:
(*(SomeStruct*)(bufPtr))
how can i do it on swift?
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 ie 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 (ie 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.