Implementing Metatypes in C
Phil Thompson
phil at river-bank.demon.co.uk
Sun Apr 13 19:10:10 EDT 2003
I want to create a type (in C) that has some additional, type specific,
information associated with it.
That type will then have many sub-types created, also in C. Instances of those
sub-types will then be created in Python.
As I understand it, I have to create a metatype for my new types so that they
get created with the correct size to contain the additional I want to store
in the type. To do this I am simply sub-typing from PyType_Type but
specifying an "appropriate" value for the tp_basicsize field. The sub-types
are then created on the heap by calling the metatype.
The problem I had was understanding what the "appropriate" value was. At first
my metatype data structure was...
struct metatype {
PyTypeObject supertype;
ExtraTypeData extra;
};
Eventually I worked out that Python allocates additional fields (as well as
PyTypeObject) when allocating new types on the heap. This is from
typeobject.c in the Python 2.3a2 source...
/* The *real* layout of a type object when allocated on the heap */
/* XXX Should we publish this in a header file? */
If I add the extra fields in my struct metatype, everything works.
Two questions...
1. Is my understanding correct, or is there a more correct way to do what I
want that avoids the problem?
2. If my solution is correct, can the structure defined in typeobject.c be
published in a header file as the comment says? Please?
Thanks,
Phil
More information about the Python-list
mailing list