Hi Lisandro!

On Fri, Mar 12, 2010 at 7:25 PM, Lisandro Dalcin <[email protected]> wrote:
>>>
>>> Can you explain me how are you managing reference counting? I think
>>> that you will need a proxy C++ class to manage incref()/decref()
>>
>> Here are the definitions of py2c_int and c2py_int:
>>
>> cdef api object c2py_int(int i):
>>    return i
>>
>
> This function will return a brand new object (or a new reference of a
> caches Python intinstance, this is a CPython implementation detail)...
> Anyway, if you call this from C/C++, you have to somehow take
> ownership of that object, of use it and throw it away (i.e. decref)
>
>>
>> cdef api int py2c_int(object i):
>>    return i
>>
>
> This functions just take a (borrowed) object as its argument...
>
> So if you do:
>
> py2c_int( c2py_int(7) )
>
> you have just leaked a reference :-) ...

Yep. But the c2py_int() is only meant to use with insert_object(),
(that I'll rename to push):

cdef api void insert_object(const_char_p name, object o):
     global_namespace.update({name: o})

where global_namespace is a dictionary. All in Cython. Example:

insert_object("a", c2py_int(3));

will this create a leak? e.g. if I do this in Cython:

insert_object("a", c2py_int(3))

there should be no leak, right? Will it create a leak when executed
from C++? I am not sure now, I'd have to test it.


>
>
>>
>> So what exactly do you mean by reference counting? Isn't this safe?
>>
>
> When you code in Cython, all is safe, and nice, and all gory details
> are taken into account... But when you move to C and start using C
> functions (it does not actually matter if they are auto-generated by
> Cython) taking and returning Cython objects, then YOU are in charge of
> following the rules and managing refcounting.
>
> In short, you have to be VERY careful about what your
> methods/functions do regarding ownership of Python references... BTW,
> Boost.Python solves this more or less nicely using proxy,
> smart-pointer-like classes for holding PyObject* references (e.g. you
> incref() in copy constructors and operator=(), decref() in
> destructors).

Right. I have to test this line in C++:

insert_object("a", c2py_int(3));

if it's leaking, then I have a problem. Well, if it's leaking, then I
can fix insert_object to steal ownership of the PyObject and I should
be fine hopefully.

>
>
> Moral: Once you get a decent knowledge of Python's C-API, you start to
> REALLY appreciate the Cython's (and Pyrex's) magic... This is the
> reason I've switched all my projects to Cython, starting from scratch
> and thorowing away all the previous hand-written C crap!
>
> Of course, working in C++ is other story... because the compiler can
> help you to manage these references (using those proxy classes).

I'd like to avoid proxy classes if possible.

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

Reply via email to