Returning objects from C extension modules.

Roy Smith roy at panix.com
Mon Jan 1 16:18:42 EST 2001


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?



More information about the Python-list mailing list