By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,996 Members | 1,343 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,996 IT Pros & Developers. It's quick & easy.

How to list the global functions from a C program

P: n/a
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
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)

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)
================================================== ============

Jul 18 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.