[Tutor] Refcount in C extensions

Izz ad-Din Ruhulessin izzaddin.ruhulessin at gmail.com
Fri Jan 14 19:49:16 CET 2011


Hi Stefan,

Thanks for your quick reply and clearing the issue up for me. Using your
answer, I rewrote the function to this:

double Py_GetAttr_DoubleFromFloat(PyObject *obj, const char *attr)
>
> {
>
> PyObject *get_attr, *py_float;
>
> int has_attr;
>
>
>> //Check if the given object has the given attribute.
>
> has_attr = PyObject_HasAttrString(obj, attr);
>
> if (has_attr == False) {
>
> return -9999.0;
>
> }
>
>
>> //Get our attribute and convert it to a double.
>
> get_attr = PyObject_GetAttrString(obj, attr);
>
> py_float = PyNumber_Float(get_attr);
>
> if (py_float == NULL) {
>
> Py_DECREF(get_attr);
>
> Py_XDECREF(py_float);
>
> return -9999.0;
>
> }
>
> double output = PyFloat_AsDouble(py_float);
>
>
>> //Garbage collect
>
> Py_DECREF(get_attr);
>
> Py_XDECREF(py_float);
>
>
>> return output;
>
> }
>
>
(False is 0)

Regarding your Cython suggestion, as a matter of coincidence I have been
reading about it in the past few days. I'm in doubt of using it however,
because I have a lot of native C code that would require rewriting if I
switched to Cython. On the other hand, your example shows that such a
one-time rewrite will pay-off big time in future development speed.

Kind regards,

Izz ad-Din
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110114/f2183fe2/attachment.html>


More information about the Tutor mailing list