How to list the global functions from a C program

F

Francesco Montorsi

Hi all,
I'm a Python newbie and I'm trying to add to my C++ program a limited
support for scripts written in python.
In particular, I'd like to load user scripts written in python, list all the
functions
he defined in the script file and then call them.

To begin I wrote into my C++ program (correctly linked to python 2.3.2):

==============================================
/* create the main module */
m_pModule = PyImport_AddModule("__main__");
m_pDict = PyModule_GetDict(m_pModule);
m_pGlobals = m_pDict;
m_pLocals = m_pDict; // is this right (globals==locals) ??

/* to try out python, I want just to force the creation of
a simple function and then call it from C */
PyRun_StringFlags("def donothing():\n\treturn 'hello'\n",
Py_file_input, m_pGlobals, m_pLocals, 0);

/* scan all the contents of the __main__ module... */
PyObject *list = PyObject_Dir(m_pGlobals);
if (!list || PyList_Check(list) == FALSE)
return;

for (int i=0,max=PyList_Size(list); i<max; i++) {

PyObject *elem = PyList_GetItem(list, i);
if (PyCallable_Check(elem) != 0) {

/* this should be a function.. */
/* HERE IS THE PROBLEM: this code is never reached */
PyObject *str = PyObject_GetAttrString(elem, "func_name");
}
}
==============================================

Everything seems to work but then when scanning the list returned
by PyObject_Dir() I never find any callable object....
what am I doing wrong ?

Thanks indeed,
Francesco Montorsi


==============================================================
The perverse principle of programming: there is always another bug. (Murphy)
==============================================================
 

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

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top