title: Convert object to byte array and vice-versa in python
body: <p>I use Python and send and receive packets to/from external c++ server (so pickle can't help) and need to serialize and deserialize python objects to/from byte arrays.</p>
  
  <p>Serialize is easy:</p>
  
  <pre><code>class MsgBase(Structure):
      def __init__(self, my_type):
          self.m_type = my_type
  
      def get_buffer(self):
          return bytearray(self)
  
      _pack_ = 1
      _fields_ = [
          ('m_type', c_uint8)]
  
  message = MsgBase(1)
  arr = message.get_buffer()
  </code></pre>
  
  <p>But how to deserialize this buffer back?</p>
  
  <p>need something like this:</p>
  
  <pre><code>message = MsgBase(0)
  message.deserialize_from_bytearray(arr)
  </code></pre>