Saturday, 15 January 2011

python - How to pack and unpack using ctypes (Structure <-> str) -


This could be a silly question, but I could not find a good answer in docs or anywhere.

If I struct have 2 symmetrical methods (pack and unpack) for defining a binary structure, struct serialization and ascending, it seems like ctypes

  ctypes * class example (structure) by import: _fields_ = [("index" , C_int), ("counter", c_int),] ctype_instance: buf = string_at (ByRef (ctype_instance), sizeof (ctype_instance)) Return def unpack bUF (CTYPE, buf): cstring = create _string_buffer (buf) ctype_instance = cast (indicator (cstring) indicator (CTYPE)) content. Return ctype_instance if __name__ == "__main__": e = Example (12, 13) buf = pack (e) E2 = unpack (for example, buf) loud (e.index == e2.index) emphasis (e.counter == E2.counter) # Note: E == E2 is incorrect for some reason ...  

There is a solution for this

FAQ:. How do I copy the bytes from a ctypes.structure

  send def (self): return buffer (auto) [:]  

normal Q: How do I copy the bytes to a CTPP? Structure from Python?

> def receiveSome (auto, bytes): fit = minute (lane (byte), ctypes.sizeof (self)) ctypes.memmove (ctypes.addressof (own), bytes, fits) pack is , and received something is such a pack_into . If you have a "safe" situation where you are unpacking in the same type of structure in the original form, then you can write a one-line memmove (addressof (y), buffer (x) [:], sizeof (Y)) to copy x to y . Of course, you probably have x . Instead of a literal packing of

, there will be a variable as the second argument.

No comments:

Post a Comment