title: Dynamically create Ctypes in Python
body: <p>I have a file that I read from which has definitions of ctypes that are used in a separate project. I can read the file and obtain all the necessary information to create a ctype that I want in Python like the name, fields, bitfields, ctype base class (Structure, Union, Enum, etc), and pack.</p>
  
  <p>I want to be able to create a ctype class from the information above. I also want these ctypes to be pickleable.</p>
  
  <p>I currently have two solutions, both of which I feel like are hacks.</p>
  
  <p><strong>Solution 1</strong></p>
  
  <p>Generate a Python code object in an appropriate ctype format by hand or with the use of something like Jinja2 and then evaluate the python code object.</p>
  
  <p>This solution has the downside of using eval. I always try to stay away from eval and I don't feel like this is a good place to use it.</p>
  
  <p><strong>Solution 2</strong></p>
  
  <p>Create a ctype dynamically in a function like so:</p>
  
  <pre><code>from ctypes import Structure
  
  def create_ctype_class(name, base, fields, pack):
      class CtypesStruct(base):
          _fields_ = fields
          _pack_ = pack
      CtypesStruct.__name__ = name
      return CtypesStruct
  
  ctype = create_ctype_class('ctype_struct_name', ctypes.Structure,
                             [('field1', ctypes.c_uint8)], 4)
  </code></pre>
  
  <p>This solution isn't so bad, but setting the name of the class is ugly and the type cannot be pickled.</p>
  
  <p>Is there a better way of creating a dynamic ctype class?</p>
  
  <p><strong>Note:</strong> I am using Python 2.7</p>