Some questions about C extensions
Duncan Grisby
dgrisby at uk.research.att.com
Thu Jun 8 09:08:04 EDT 2000
In article <etdu2f69rhz.fsf at w20-575-109.mit.edu>,
Alex <cut_me_out at hotmail.com> wrote:
>-- Deallocation of memory for strings returned by python functions:
> Do I have to do it, or is it somehow taken care of? If I have
> something like
>
> if (!PyArg_ParseTuple (args, "s", &sequence)) {
> return NULL;}
>
> do I have to do a free (sequence); at some point? I would have
> thought so, but it seems to be giving me a Seg fault.
No -- sequence points to the string which is inside the Python string
object.
>-- Reference counts for elements of brand new tuples. Why do I have to
> do a Py_INCREF on an object before I assign it to a new tuple with
> PyTuple_SetItem? Since it seems as though you have to do a Py_INCREF
> every time anyway, is there a function like PyTuple_SetItem that will
> do it for you? The comment in the C API manual about this is very
> cryptic, BTW.
You don't necessarily have to do Py_INCREF when you insert things in a
tuple. I often write code which does something like:
PyObject *a, *b, *t;
a = PyInt_FromLong(1234);
b = PyString_FromString("Hello");
t = PyTuple_New(2);
PyTuple_SetItem(t, 0, a);
PyTuple_SetItem(t, 1, b);
/* ... do something with the tuple... */
Py_DECREF(t);
That way, when the tuple is deleted, the int and string objects inside
it are also deleted.
Cheers,
Duncan.
--
-- Duncan Grisby \ Research Engineer --
-- AT&T Laboratories Cambridge --
-- http://www.uk.research.att.com/~dpg1 --
More information about the Python-list
mailing list