Returning objects from C extension modules.

Donn Cave donn at u.washington.edu
Tue Jan 2 13:25:29 EST 2001


Quoth Roy Smith <roy at panix.com>:
| I've played around a bit with building extension modules in C, and I think 
| I've got the hang of the basic stuff.  I (think) I understand how to use 
| Py_BuildValue() to return simple values, and lists, tuples, or dictionaries 
| of these.
|
| But, what I don't get is how to implement a class and return an object of 
| that class.  For example, let's say I've got a function in C which looks like 
| this:
|
| typedef struct {
|    int weapon_count;
|    char name[MAX_NAME];
| } record;
|
| record *get_record ()
| {
|    record *rec_ptr;
|
|    rec_ptr = (record *) malloc (sizeof (record));
|    rec_ptr->weapon_count = 3;
|    strcpy (rec_ptr->name, "spanish inquisition");
|    return rec_ptr;
| }
|
| and I want to turn it into a python module which returns an object of class 
| sketch, as if I had done something like:
|
| class sketch:
|    def __init__ (self)
|       self.weapon_count = 3
|       self.name = "spanish inquisition"
|
| Do I need to have my extension module return a tuple of values, then build a 
| thin wrapper in python which creates the class, instantiates an object of 
| that class, and then copies the items of the tuple into the object?  Or is 
| there something more straight-forward?

If it's appropriate for your application, you can make a "type" in C.
There are plenty of examples in the source tree - look for PyObject_New()
in the Modules subdirectory.  I didn't see anything about this in the
Extending document, to my surprise.

The resulting object is like a class instance, but isn't one.

I think a bona fide class is most easily created, as you surmise, in
Python instead of C.  That's a good alternative to a "type" object,
if the C functions can make do with ordinary Python data types.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list