How to list the global functions from a C program

Discussion in 'Python' started by Francesco Montorsi, Jan 14, 2005.

  1. 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)
    ==============================================================
     
    Francesco Montorsi, Jan 14, 2005
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Xiangliang Meng
    Replies:
    1
    Views:
    1,615
    Victor Bazarov
    Jun 21, 2004
  2. Jack Diederich
    Replies:
    0
    Views:
    454
    Jack Diederich
    Jan 14, 2005
  3. Ross A. Finlayson
    Replies:
    19
    Views:
    606
    Keith Thompson
    Mar 10, 2005
  4. Ali Shirvani

    How get list of functions in current C program

    Ali Shirvani, Nov 17, 2008, in forum: C Programming
    Replies:
    6
    Views:
    1,006
    James Harris
    Nov 18, 2008
  5. User1014
    Replies:
    3
    Views:
    193
    Richard Cornford
    Dec 1, 2006
Loading...

Share This Page