embedding Python in C

Gordon McMillan gmcm at hypernet.com
Thu Dec 23 23:22:27 EST 1999


Curtis Jensen wrote:
> 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? 

No. You just imported a module named foo. I kind of expected 
your C code exposed a method (see the extending docs) that 
took a PyObject, checked that it was an instancetype, then 
looked for an attribute named a on the object. So your Python 
might look like:

import CJs_extension

foo = Foo()
CJs_extension.do_something(foo)

Then your C code can be fairly straightforward. Rooting around 
through Python namespaces looking for an instance of Foo 
could take a whole lot of code ;-).

> 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



- Gordon




More information about the Python-list mailing list