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

J

JM

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,"NumLegs"));

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
 
J

JM

If anyone is interested in the solution:

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

JG
 
G

Greg Chapman

If anyone is interested in the solution:

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

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top