Skip to content

Commit 75e6a7b

Browse files
committed
ctypes: Return existing pointer when possible
Addresses gh-46376
1 parent b273837 commit 75e6a7b

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

Lib/test/test_ctypes/test_keeprefs.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,33 @@ def test_p_cint(self):
9898
x = pointer(i)
9999
self.assertEqual(x._objects, {'1': i})
100100

101+
def test_pp_ownership(self):
102+
d = c_int(123)
103+
n = c_int(456)
104+
105+
p = pointer(d)
106+
pp = pointer(p)
107+
108+
self.assertIs(pp._objects['1'], p)
109+
self.assertIs(pp._objects['0']['1'], d)
110+
111+
pp.contents.contents = n
112+
113+
self.assertIs(pp._objects['1'], p)
114+
self.assertIs(pp._objects['0']['1'], n)
115+
116+
self.assertIs(p._objects['1'], n)
117+
self.assertEqual(len(p._objects), 1)
118+
119+
del d
120+
del p
121+
122+
self.assertIs(pp._objects['0']['1'], n)
123+
self.assertEqual(len(pp._objects), 2)
124+
125+
del n
126+
127+
self.assertEqual(len(pp._objects), 2)
101128

102129
class PointerToStructure(unittest.TestCase):
103130
def test(self):

Modules/_ctypes/_ctypes.c

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5129,6 +5129,7 @@ static PyObject *
51295129
Pointer_get_contents(CDataObject *self, void *closure)
51305130
{
51315131
StgDictObject *stgdict;
5132+
PyObject *keep, *pointer_probe, *pointer_to_pointer;
51325133

51335134
if (*(void **)self->b_ptr == NULL) {
51345135
PyErr_SetString(PyExc_ValueError,
@@ -5138,6 +5139,28 @@ Pointer_get_contents(CDataObject *self, void *closure)
51385139

51395140
stgdict = PyObject_stgdict((PyObject *)self);
51405141
assert(stgdict); /* Cannot be NULL for pointer instances */
5142+
5143+
keep = GetKeepedObjects(self);
5144+
if (keep != NULL) {
5145+
// check if it's a pointer to a pointer:
5146+
// pointers will have '0' key in the _objects
5147+
5148+
pointer_probe = PyDict_GetItemString(keep, "0");
5149+
5150+
if (pointer_probe != NULL) {
5151+
pointer_to_pointer = PyDict_GetItemString(keep, "1");
5152+
if (pointer_to_pointer == NULL) {
5153+
PyErr_SetString(PyExc_ValueError,
5154+
"Unexpected NULL pointer in _objects");
5155+
return NULL;
5156+
}
5157+
// don't construct a new object,
5158+
// return existing one instead to preserve refcount
5159+
Py_INCREF(pointer_to_pointer);
5160+
return pointer_to_pointer;
5161+
}
5162+
}
5163+
51415164
return PyCData_FromBaseObj(stgdict->proto,
51425165
(PyObject *)self, 0,
51435166
*(void **)self->b_ptr);

0 commit comments

Comments
 (0)