Embedding: Problem with CallObject
Bernhard Herzog
bh at intevation.de
Thu Jun 14 05:23:51 EDT 2001
"James Turner" <jamwt at jamwt.com> writes:
> Hello.
>
> I'm just starting to play with embedding Python in C, and I'm getting a
> huge headache from trying to figure out what's wrong with my code here:
>
> --test.c--
> #include <Python.h>
>
> int main(int argc, char** argv)
> {
> PyObject *str,*mod,*flist,*func,*args;
> Py_Initialize();
> str = PyString_FromString("anything");
>
> /*Import mod */
> mod = PyImport_Import(PyString_FromString("one") );
This is a memory leak, because PyString_FromString returns a new
reference. It would probably be easier to use PyImport_ImportModule
because it takes a C string as argument and not a Python string object.
>
> flist = PyModule_GetDict(mod);
> func = PyDict_GetItemString(flist,PyString_FromString("out"));
PyDict_GetItemString takes a char* as the second argument, not a string
object, so it should be:
func = PyDict_GetItemString(flist, "out");
Your version most likely returns NULL causing the segfault later.
> args = PyTuple_New(1);
> PyTuple_SetItem(args, 0,str);
>
> /* FAILS HERE!! */
> PyObject_CallObject(func,args);
You should check the return value of PyObject_CallObject and DECREF it.
> Py_XDECREF(flist);
> Py_XDECREF(func);
Don't DECREF func because it's a borrowed reference. Likewise for flist.
> Py_XDECREF(args);
> Py_XDECREF(mod);
> Py_XDECREF(str);
>
> Py_Finalize();
> return 0;
> }
HTH,
Bernhard
--
Intevation GmbH http://intevation.de/
Sketch http://sketch.sourceforge.net/
MapIt! http://mapit.de/
More information about the Python-list
mailing list