[pypy-dev] Builtin types

Thomas Heller theller at python.net
Fri Jan 24 09:01:11 CET 2003

Bengt Richter <bokr at oz.net> writes:

> I have some thoughts for decribing C structures (and anything else
> digital) in a canonical abstract way. I'll call such a decription
> a meta-representation, and a function that produces it from a Python
> object is meta_repr(python_object) => meta_rep_obj. The reverse
> operation is meta_eval ;-)
> The basis for meta_repr is that it capture and meta-represent
> (type, id, value) for an object in a pure abstract form.
> The abstract basis for storing the information is a bitvector
> object with attribute names that specify slices of the bitvector.
> I.e., there is an effective dict like {'slicename':(lo,hi)} and
> __getattr__ uses it so that bvec.slicename refers to bvec[lo:hi] etc.
> This is pure and abstract data, but you can see that interpreted
> little-endianly you can very straightforwardly lay out a C struct
> with whatever field widths and alignments you want.
> I also want to make a way to create subclasses of the base bitvector
> class that can have specified size and named slices as class variable
> info shared by instances. This is very analogous to a C struct
> definition, and BTW also permits union by just defining overlapping
> named slices.

This all sounds very similar to what is already implemented in ctypes ;-)

This is a the structure which stores to information for one field of a
C structure or union:

typedef struct {
	int offset;
	int size;
	int index;			/* Index into CDataObject's
					   object array */
	PyObject *proto;		/* a type or NULL */
	GETFUNC getfunc;		/* getter function if proto is NULL */
	SETFUNC setfunc;		/* setter function if proto is NULL */
} CFieldObject;

'offset' is what you call 'lo', and 'offset + size' is your 'hi'
attribute.  'proto' (I should probably have chosen a better name) is a
Python object holding information about the field type (such as
alignment requirements and storage size), and 'getfunc' and 'setfunc'
are pointers to functions which are able to convert the data from
Python to C and vice versa.

Instances of these CFieldObjects populate the class dict of ctypes
Structure and Union subclasses, they are created by their respective
metaclass from the _fields_ attribute, and are used as attribute
descriptors to expose the fields to Python.


More information about the Pypy-dev mailing list