tp_free and tp_dealloc?
Jason Orendorff
jason at jorendorff.com
Thu Dec 20 13:09:56 EST 2001
Robert Nikander wrote:
> I am writing my first extension types and am having a couple problems. One
> is that I and am confused about the tp_free vs the tp_dealloc slots in
> PyTypeObject. [...] So: 'tp_free' is opposite 'tp_alloc'
> and 'tp_new' is opposite 'tp_dealloc'
I think you are right.
* tp_dealloc is the general-purpose destructor, and Python calls it
when the object needs to be deallocated. tp_dealloc should destroy
or dereference the object's members, then deallocate the memory
for the object itself. If your object implements tp_free, then
tp_dealloc should use tp_free to do the final deallocation.
That is, the last line of tp_alloc should be:
self->ob_type->tp_free(self);
* tp_free only deallocates the memory that Python allocated for the
object. It seems the core Python types only implement this when
Py_TPFLAGS_BASETYPE is defined. They use either _PyObject_Del
or _PyObject_GC_Del in this slot.
> Also a Dog works fine but a Python subclass segfaults when the object is
> dealloc'd.
When you use PyArg_ParseTuple("s"), the pointer you get is a pointer
to internal data in the string object. Don't free it and don't store
it that way; instead you can either (a) maintain a reference to the
string object or (b) strdup() the buffer and keep your own copy.
## Jason Orendorff http://www.jorendorff.com/
More information about the Python-list
mailing list