Access to C functions from a python class using self ?

christophe grimault christophe.grimault at novagrid.com
Mon Dec 30 06:59:16 EST 2002


Hi there,

I've been looking to 'ext & emb python', swig, cxx, ... for quite some 
time now, and I still can't figure out how to do the kind of stuff 
explained below...

I define a class in python, let's say this simple class, just for the 
purpose of discussion :

class Vector:
    def __init__(self, x1, x2, x3):
        self.x1, self.x2, self.x3 = x1, x2, x3

    def sum(self):
        return self.x1 + self.x2 + self.x3

Now, I find that sum is slow, and I want to speedup things by replacing 
sum by a call to C.
Looking at the manual, I can write something like:

static PyObject *sum( PyObject *self, PyObject *args )

and  the manual tells me how to access elements passed in args, but does 
not tell how to access elements (in fact attributes) of self. How can I 
retrieve self.x1, self.x2, and self.x3 as defined in the python class 
from *self passed to the C function ?

The goal for me is to create classes quickly in Python. These classes 
have, say, a constructor and 5 to 30 methods. The object itself is quite 
complex (lots of attributes of different types) and only one or two 
method need very high speed and thus, must call C.

And i want to avoid passing all the attributes needed by those C calls 
by increasing the *args !

Any help would be appreciated !

Christophe




More information about the Python-list mailing list