title: How to pack and unpack using ctypes (Structure <-> str)
body: <p>This might be a silly question but I couldn't find a good answer in the docs or anywhere.</p>
  
  <p>If I use <strong>struct</strong> to define a binary structure, the struct has 2 symmetrical methods for serialization and deserialization (pack and unpack) but it seems <strong>ctypes</strong> doesn't have a straightforward way to do this. Here's my solution, which feels wrong:</p>
  
  <pre><code>from ctypes import *
  
  class Example(Structure):
      _fields_ = [
          ("index", c_int),
          ("counter", c_int),
          ]
  
  def Pack(ctype_instance):
      buf = string_at(byref(ctype_instance), sizeof(ctype_instance))
      return buf
  
  def Unpack(ctype, buf):
      cstring = create_string_buffer(buf)
      ctype_instance = cast(pointer(cstring), POINTER(ctype)).contents
      return ctype_instance
  
  if __name__ == "__main__":
      e = Example(12, 13)
      buf = Pack(e)
      e2 = Unpack(Example, buf)
      assert(e.index == e2.index)
      assert(e.counter == e2.counter)
      # note: for some reason e == e2 is False...
  </code></pre>