Remove entity self-reference cycle
UIEntity::init() stored self->data->self = (PyObject*)self with Py_INCREF(self), creating a reference cycle that prevented entities from ever being freed. The matching Py_DECREF never existed. Fix: Remove the `self` field from UIEntity entirely. Replace all read sites (iter next, getitem, get_perspective, entities_in_radius) with PythonObjectCache lookups using serial_number, which uses weak references and doesn't prevent garbage collection. Also adds tp_dealloc to PyUIEntityType to properly clean up the shared_ptr and weak references when the Python wrapper is freed. Closes #266, closes #275 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
71eb01c950
commit
a12e035a71
5 changed files with 123 additions and 30 deletions
|
|
@ -1442,13 +1442,7 @@ PyObject* UIGrid::get_perspective(PyUIGridObject* self, void* closure)
|
|||
}
|
||||
}
|
||||
|
||||
// Legacy: If the entity has a stored Python object reference
|
||||
if (locked->self != nullptr) {
|
||||
Py_INCREF(locked->self);
|
||||
return locked->self;
|
||||
}
|
||||
|
||||
// Otherwise, create a new base Entity object
|
||||
// Create a new base Entity object
|
||||
auto type = &mcrfpydef::PyUIEntityType;
|
||||
auto o = (PyUIEntityObject*)type->tp_alloc(type, 0);
|
||||
if (o) {
|
||||
|
|
@ -1936,11 +1930,12 @@ PyObject* UIGrid::py_entities_in_radius(PyUIGridObject* self, PyObject* args, Py
|
|||
for (size_t i = 0; i < entities.size(); i++) {
|
||||
auto& entity = entities[i];
|
||||
|
||||
// Return stored Python object if it exists
|
||||
if (entity->self != nullptr) {
|
||||
Py_INCREF(entity->self);
|
||||
PyList_SET_ITEM(result, i, entity->self);
|
||||
} else {
|
||||
// Check cache first to preserve derived class identity
|
||||
PyObject* py_entity = nullptr;
|
||||
if (entity->serial_number != 0) {
|
||||
py_entity = PythonObjectCache::getInstance().lookup(entity->serial_number);
|
||||
}
|
||||
if (!py_entity) {
|
||||
// Create new Python Entity wrapper
|
||||
auto pyEntity = (PyUIEntityObject*)entity_type->tp_alloc(entity_type, 0);
|
||||
if (!pyEntity) {
|
||||
|
|
@ -1949,8 +1944,9 @@ PyObject* UIGrid::py_entities_in_radius(PyUIGridObject* self, PyObject* args, Py
|
|||
}
|
||||
pyEntity->data = entity;
|
||||
pyEntity->weakreflist = NULL;
|
||||
PyList_SET_ITEM(result, i, (PyObject*)pyEntity);
|
||||
py_entity = (PyObject*)pyEntity;
|
||||
}
|
||||
PyList_SET_ITEM(result, i, py_entity);
|
||||
}
|
||||
|
||||
return result;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue