embedding Python in C

Curtis Jensen cjensen at be-research.ucsd.edu
Thu Dec 23 16:51:02 EST 1999


Gordon McMillan wrote:
> 
> Curtis Jensen asks:
> 
> > From a C file, how can I get values from a Python Class?
> > For Example:
> >
> > File: Test.py
> > class Klass:
> >   def __init__(self):
> >     self.a = 1
> >     self.b = 2
> >     self.c = 3
> >
> > How can I get the values of a,b, and c from within a C function?
> > Thanks
> 
> Assuming you mean "from an instance of Klass", the answer
> is the same way you would in Python. Well, in dynamic
> Python. The equivalent of getattr(obj, name) is
> PyObject_GetAttrString(o, name).
> 
> - Gordon

Suppose I have an instance of Klass called foo.  In the C code I have:
    int tmp;
    PyObject *value;
    PyObject *pmod;

    pmod = PyImport_ImportModule ("foo");
    value = PyObject_GetAttrString (pmod, "a");
    PyArg_ParseTuple(value, "i", &tmp);
    printf("Value = %d\n",tmp);

I should get "Value = 1" outputed to the screen right?  I don't; I get
some realy big number.  I'm not sure what is wrong.  I've tried several
different combinations of variables and pointers and I can't get it. 
What's wrong with the code?  Thanks.

-- 
Curtis Jensen
cjensen at be-research.ucsd.edu
http://www-bioeng.ucsd.edu/~cjensen/
FAX (425) 740-1451




More information about the Python-list mailing list