Connecting Tech Pros Worldwide Forums | Help | Site Map

Accessing members of Python class from C++ (Embedded Python)????

JM
Guest
 
Posts: n/a
#1: Jul 18 '05
Hello everyone,

Does anybody know about, have documentation on, or have any code
samples on how to access class members from a python class in C++.

Say I have a simple python script:

---------------------------
class Animal:
NumLegs = 5
Size = 4.5
---------------------------

How exactly do you access these members from C++. I know how to get
the member if I know its name, ie.

pkObject = PyDict_GetItemString(pkDict, "Animal");
int uiNumLegs = PyInt_AsLong(PyObject_GetAttrString(pkObject,"NumL egs"));

But how do you iterate through all the class members and print their
names and values? This is easy to do for basic variables, but I can't
seem to do it for class variables.

Any help would be much apprecited. This is driving me nuts.

JG

JM
Guest
 
Posts: n/a
#2: Jul 18 '05

re: Accessing members of Python class from C++ (Embedded Python)????


If anyone is interested in the solution:

pDict=PyObject_GetAttrString(PyObject,"__dict__") will get the local
symbol table (a dictionary) for the class.

JG

jgerard@fluid-studios.ca (JM) wrote in message news:<fcd83a69.0308261502.56809870@posting.google. com>...[color=blue]
> Hello everyone,
>
> Does anybody know about, have documentation on, or have any code
> samples on how to access class members from a python class in C++.
>
> Say I have a simple python script:
>
> ---------------------------
> class Animal:
> NumLegs = 5
> Size = 4.5
> ---------------------------
>
> How exactly do you access these members from C++. I know how to get
> the member if I know its name, ie.
>
> pkObject = PyDict_GetItemString(pkDict, "Animal");
> int uiNumLegs = PyInt_AsLong(PyObject_GetAttrString(pkObject,"NumL egs"));
>
> But how do you iterate through all the class members and print their
> names and values? This is easy to do for basic variables, but I can't
> seem to do it for class variables.
>
> Any help would be much apprecited. This is driving me nuts.
>
> JG[/color]
Greg Chapman
Guest
 
Posts: n/a
#3: Jul 18 '05

re: Accessing members of Python class from C++ (Embedded Python)????


On 27 Aug 2003 10:14:02 -0700, jgerard@fluid-studios.ca (JM) wrote:
[color=blue]
>If anyone is interested in the solution:
>
>pDict=PyObject_GetAttrString(PyObject,"__dict__ ") will get the local
>symbol table (a dictionary) for the class.[/color]

This may not be relevant to your needs, but a class's __dict__ only has
references to the attributes actually declared in the class; it doesn't have
inherited attributes. If you need access to all the attributes of a class, use
PyObject_Dir(aClass), which returns a list of all attribute names declared in
the class and it's superclasses (it's the C equivalent of the dir builtin). You
can then use PyObject_GetAttr(aClass, attrname) to fetch the attributes
themselves.

---
Greg Chapman

Closed Thread


Similar Python bytes