How to call a python function in C++
Joseph A Knapka
jknapka at earthlink.net
Sun Oct 7 19:58:08 EDT 2001
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.
> ......
> PyObject * arglist;
> arglist = Py_BuildValue("(s1000)", buf);
> PyObject *result;
>
> result = PyEval_CallObject(my_callback, arglist);
> Py_DECREF(arglist);
>
> .......
>
> I compiled them to seprate object file and link them to be provapimodule.so.
>
> I got no error in compiling, but when I load the provapi in python,
> there is an error:
>
> >ImportError: ./provapimodule.so: undefined symbol: my_callback.
See my comment above. There is essentially no link step at build time
for a Linux shared library; the Linux dynamic loader attempts to resolve
linkage at load time, so that's why you see the error here rather than
at build time.
> Then I try to remove "static" in defination of my_callback. This time, I
> can load the module without error, and I can access provapi.my_callback
> too. But I met this:
>
> >>> provapi.my_set_callback(binstr,happy)
> Traceback (innermost last):
> File "<stdin>", line 1, in ?
> AttributeError: my_set_callback
>
> I do not know what does this mean?
You -have- initialized the module method table using
Py_InitModule(), haven't you? If not, that's the
problem.
> I am using g++ (gcc version 2.96 20000731) and Linux 7.1. Python 1.5.2.
>
> Anyone can help me, thank you!
>
> clio
HTH,
-- 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