Reference count question

Fredrik Lundh fredrik at pythonware.com
Wed Feb 2 13:06:48 EST 2005


"cedric paille" wrote:

> I'm making python's modules to extend my application's functions with a built in script editor.
> At now all works very well, but i'd like to know if i'm not forgetting some references inc/dec....
>
> Here is a portion of my code:
>
> static PyObject *
> Scene_GetNodeGraph(PyObject *self, PyObject *args)
> {
>  NodeGraph* Ng = NodeGraph::GetInstance();
>  std::vector<String> NodG;
>  Ng->GetNodeGraph(NodG);
>  PyObject* List = PyList_New(NodG.size());

after this operation, this function "owns" the object.

you should check for a NULL value, though.  PyList_New may
fail.  adding "if (!List) return NULL;" should do the trick.

>  PyObject* Str = NULL;
>  std::vector<String>::iterator it = NodG.begin();
>  int i = 0;
>  for (;it != NodG.end();it++)
>  {
>    Str = PyString_FromString(it->AsChar());

after this operation, the function "owns" the string.

you should check for a NULL value, though.  PyString_FromString
may fail (don't forget to release the list).

>    PyList_SetItem(List,i,Str);

after this operation, the list "owns" the string.

you should check the return value, though.  PyList_SetItem may (in
theory) fail.

     i++;
  }
  return List;

this hands List ownership over to the caller.

}

> Can someone take a look at this and tell me if i must add some inc/decref ?

the reference handling looks correct, but you might wish to add some error
handling to avoid crashes under low-memory conditions.

</F> 






More information about the Python-list mailing list