On Mar 20, 2010, at 11:27 PM, Ondrej Certik wrote:

[...]

> This line however is leaking:
>
>    int i = py2c_int(python->pull("i"));
>
> because pull("i") increfs "i", but py2c_int() doesn't do anything with
> the reference, so nothing decrefs it. What is the best way to fix
> this?
>
>
> Here is one way:
>
> PyObject *tmp = python->pull("i");
> int i = py2c_int(tmp);
> Py_DECREF(tmp);
>
> But this is super annoying from the user experience, because this is
> the code that the user has to write by hand and I want to make this as
> easy as possible.

This is why Cython is so nice :).

> Another option is to create a function pull_int():
>
> int Python::pull_int(const char* name)
> {
>    PyObject *tmp = python->pull("i");
>    int i = py2c_int(tmp);
>    Py_DECREF(tmp);
>    return i;
> }
>
> and the user would use:
>
> int i = p->pull_int("i");
>
> there would be no leak and it would be very easy to use. However, this
> means that I have to manually write C++ methods like pull_int() for
> every single of my py2c_* conversion functions, which is annoying too.
> Yet another option seems to be to use some macro/function to do the
> above, e.g. usage would be something like:
>
> int i = F(py2c_int, p->pull_int("i"));
>
> but this is still too complex from the user perspective. I might
> figure out some way to construct the pull_int() methods
> semiautomatically using some macros.
>
> What would you suggest me?


I see two options. The first, is to make a "pull_borrowed" which does  
a decref (or skips an incref) before returning the value. This will  
work if what you're pulling from is actually a dictionary, as the  
object will be pointed to elsewhere so won't go away (until the  
dictionary is modified). The other option is to have your py2c_int  
function "steal" a reference. (How often do you need the old one  
around once you've converted it to an int?)

Unfortunately, both require the user to be reference-count aware. I  
think the nicest interface is pull_T for several common T.

- Robert

_______________________________________________
Cython-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/cython-dev

Reply via email to