another-pypy / ctypes_configure / dumpcache.py

import os, sys
import ctypes


def dumpcache(referencefilename, filename, config):
    dirname = os.path.dirname(referencefilename)
    filename = os.path.join(dirname, filename)
    f = open(filename, 'w')
    print >> f, 'import ctypes'
    print >> f
    names = config.keys()
    names.sort()
    print >> f, '__all__ = %r' % (tuple(names),)
    print >> f
    for key in names:
        val = config[key]
        if isinstance(val, (int, long)):
            f.write("%s = %d\n" % (key, val))
        elif val is None:
            f.write("%s = None\n" % key)
        elif isinstance(val, ctypes.Structure.__class__):
            f.write("class %s(ctypes.Structure):\n" % key)
            f.write("    _fields_ = [\n")
            for k, v in val._fields_:
                f.write("        ('%s', %s),\n" % (k, ctypes_repr(v)))
            f.write("    ]\n")
        elif isinstance(val, (tuple, list)):
            for x in val:
                assert isinstance(x, (int, long, str)), \
                       "lists of integers or strings only"
            f.write("%s = %r\n" % (key, val))
        else:
            # a simple type, hopefully
            f.write("%s = %s\n" % (key, ctypes_repr(val)))
    f.close()
    print 'Wrote %s.' % (filename,)
    sys.stdout.flush()

def ctypes_repr(cls):
    # ctypes_configure does not support nested structs so far
    # so let's ignore it
    if isinstance(cls, ctypes._SimpleCData.__class__):
        return "ctypes." + cls.__name__
    if hasattr(cls, '_length_') and hasattr(cls, '_type_'):  # assume an array
        return '%s*%d' % (ctypes_repr(cls._type_), cls._length_)
    raise NotImplementedError("saving of object with type %r" % type(cls))
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.