Skip to content

Commit dc0014f

Browse files
authored
Merge pull request #3590 from cherez/weakrefable_textures
Add weak reference support to Texture
2 parents f5d4b90 + 35afcc0 commit dc0014f

File tree

3 files changed

+15
-0
lines changed

3 files changed

+15
-0
lines changed

src_c/include/_pygame.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -556,6 +556,7 @@ struct pgTextureObject {
556556
pgRendererObject *renderer;
557557
int width;
558558
int height;
559+
PyObject *weakreflist;
559560
};
560561

561562
typedef struct {

src_c/render.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -682,6 +682,7 @@ texture_from_surface(PyObject *self, PyObject *args, PyObject *kwargs)
682682
Py_XINCREF(new_texture->renderer);
683683
new_texture->width = surf->w;
684684
new_texture->height = surf->h;
685+
new_texture->weakreflist = NULL;
685686
return (PyObject *)new_texture;
686687
}
687688

@@ -1169,6 +1170,9 @@ texture_dealloc(pgTextureObject *self, PyObject *_null)
11691170
if (self->texture) {
11701171
SDL_DestroyTexture(self->texture);
11711172
}
1173+
if (self->weakreflist) {
1174+
PyObject_ClearWeakRefs((PyObject *)self);
1175+
}
11721176
Py_TYPE(self)->tp_free(self);
11731177
}
11741178

@@ -1289,6 +1293,7 @@ static PyTypeObject pgTexture_Type = {
12891293
.tp_basicsize = sizeof(pgTextureObject),
12901294
.tp_dealloc = (destructor)texture_dealloc,
12911295
.tp_doc = DOC_SDL2_VIDEO_TEXTURE,
1296+
.tp_weaklistoffset = offsetof(pgTextureObject, weakreflist),
12921297
.tp_methods = texture_methods,
12931298
.tp_init = (initproc)texture_init,
12941299
.tp_new = PyType_GenericNew,

test/render_test.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
import gc
12
import unittest
3+
import weakref
24

35
import pygame
46
import pygame._render as _render
@@ -465,6 +467,13 @@ def test_draw(self):
465467
for x in range(64, 82):
466468
self.assertEqual(pygame.Color(80, 120, 160, 255), result.get_at((x, 50)))
467469

470+
def test_garbage_collection(self):
471+
reference = weakref.ref(self.texture)
472+
self.assertTrue(reference() is self.texture)
473+
del self.texture
474+
gc.collect()
475+
self.assertIsNone(reference())
476+
468477
def test_update(self):
469478
surface = pygame.Surface((100, 100))
470479
surface.fill(pygame.Color(80, 120, 160, 128))

0 commit comments

Comments
 (0)