Embedding: Creating / Deleting CObjects?!

Bernhard Herzog herzog at online.de
Wed Jul 21 16:34:25 EDT 1999


Bjoern Giesler <un4e at rz.uni-karlsruhe.de> writes:

> I'm truly baffled. I'm trying to define a backend for my embedded Python
> system, and the corresponding C routines seem to work, but the program
> crashes somewhere in the Python library routines, dances the Fandango all
> over my internal object representation, and whatnot. 
> 
> I'm posting a couple of fragments of my code, just so that somebody can tell
> me whether this is the canonical way of handling things (this side of Python
> is not exactly well documented...) 
> 
> /* Content destructor function */
> static void
> PLPythonDestructor(proplist_t obj)
> {
>   PLRelease(obj);
> }
> 
> /* CObject Creator */
> static PyObject *
> PLPythonNewInstance(PyObject *self, PyObject *args)
> {
>   proplist_t plClassName, plArgs;
>   instance_t instance;
>   char *className;
>   PyObject *pyArgs, *retval;
> 
>   printf("NewInstanceVar\n");
> 
>   if(!PyArg_ParseTuple(args, "sO", &className, &pyArgs))
>     return NULL;
> 
>   plArgs = PLPy2PLObject(pyArgs); /* NULL is OK here */
>   plClassName = PLMakeString(className);
>   instance = PLObjectNewInstance(plClassName, plArgs); /* [My own braindead
> 							  class system.
> 							  Works, though.] */
>   if(plClassName)
>     PLRelease(plClassName);
>   if(plArgs)
>     PLRelease(plArgs);
> 
>   if(!instance)
>     {
>       PyErr_SetString(PyExc_RuntimeError, "Couldn't create new instance");
>       return NULL;
>     }
>   retval = PyCObject_FromVoidPtr((void *)instance,
> 				 PLPythonDestructor);
>   Py_INCREF(retval);

This INCREF creates a memory leak. PyCObject_FromVoidPtr returns a new
CObject which you can return as is.

>   return retval;
> }
> 
> /* CObject Destructor */
> static PyObject *
> PLPythonDeleteInstance(PyObject *self, PyObject *args)
> {
>   instance_t instance;
>   PyObject *instanceObject;
> 
>   printf("DeleteInstance\n");
> 
>   if(!PyArg_ParseTuple(args, "O", &instanceObject))
>     return NULL;
> 
>   /*
>   instance = (instance_t) PyCObject_AsVoidPtr(instanceObject);
>   PLObjectDeleteInstance(instance);
>   */
> 
>   Py_XDECREF(instanceObject);

This DECREF is wrong here, because PyArg_ParseTuple does not increase
the refcount of *instanceObject.

>   return Py_None;
> }


-- 
Bernhard Herzog	  | Sketch, a python based drawing program
herzog at online.de  | http://www.online.de/home/sketch/




More information about the Python-list mailing list