How to call a python function in C++

Joseph A Knapka jknapka at earthlink.net
Sun Oct 7 21:10:08 EDT 2001


Joseph A Knapka wrote:
> 
> clio wrote:
> >
> > Hi,
> > Here is a very confusing problem. I am trying to call a python function
> > in C. I build a .cxx which have following functions:
> >
> > ......
> > static PyObject *my_callback=NULL;
> >
> > static PyObject * my_set_callback(PyObject * dummy,PyObject * args)
> >
> >   {
> >             PyObject *result = NULL;
> >             PyObject *temp;
> >
> >             if (PyArg_ParseTuple(args, "O:set_callback", &temp)) {
> >                 if (!PyCallable_Check(temp)) {
> >                     PyErr_SetString(PyExc_TypeError, "parameter must be
> > callable");
> >                     return NULL;
> >                 }
> >                 Py_XINCREF(temp);         /* Add a reference to new
> > callback */
> >                 Py_XDECREF(my_callback);  /* Dispose of previous callback */
> >                 my_callback = temp;       /* Remember new callback */
> >                 /* Boilerplate to return "None" */
> >                 Py_INCREF(Py_None);
> >                 result = Py_None;
> >             }
> >             return result;
> >         }
> > ..........
> > Acctually, this code is from online manual. Then in another c++ program
> > I have this:
> >
> > extern PyObject *my_callback;
> 
> This will not work because my_callback is declared static
> and therefor is visible only within its source file. Try
> 
> PyObject *my_callback;
> 
> instead.

Sorry to reply to myself, but I just noticed this advice
could be misinterpreted. In the first file,

static PyObject* my_callback;

should just be

PyObject* my_callback;

The "extern PyObject* my_callback;" in the second file
is correct.

-- Joe
# "You know how many remote castles there are along the
#  gorges? You can't MOVE for remote castles!" - Lu Tze re. Uberwald
# Linux MM docs:
http://home.earthlink.net/~jknapka/linux-mm/vmoutline.html



More information about the Python-list mailing list