8000 gh-46376: add (failing) tests for ctypes/pointer/cast/set_contents · python/cpython@0116633 · GitHub
[go: up one dir, main page]

Skip to content

Commit 0116633

Browse files
committed
gh-46376: add (failing) tests for ctypes/pointer/cast/set_contents
Previous attempt to fix gh-46376 was incomplete and overall it didn't succeed, and was reverted in 3.11. However, we have discovered some dangerous issues with ctypes, that aren't fixed or documented anywhere. This commit adds tests (@expectedfailure) so at least developers are aware of situations where memory might be corrupted, leaked or when changing a pointer value might have no effect. Hopefully, we should be able to remove @expectedfailure in the future, with new shiny ctypes implementation or at least a bugfix.
1 parent 0a26aa5 commit 0116633

File tree

4 files changed

+499
-5
lines changed

4 files changed

+499
-5
lines changed

Lib/test/test_ctypes/test_arrays.py

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1+
import gc
12
import ctypes
23
import sys
34
import unittest
45
import warnings
5-
from ctypes import (Structure, Array, sizeof, addressof,
6+
import weakref
7+
from ctypes import (Structure, Array, sizeof, addressof, POINTER, pointer,
68
create_string_buffer, create_unicode_buffer,
79
c_char, c_wchar, c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint,
810
c_long, c_ulonglong, c_float, c_double, c_longdouble)
@@ -279,6 +281,32 @@ def test_deprecation(self):
279281
with self.assertWarns(DeprecationWarning):
280282
CharArray = ctypes.ARRAY(c_char, 3)
281283

284+
def test_ptr_reuse(self):
285+
w = weakref.WeakValueDictionary()
286+
arr = 3 * POINTER(c_short)
287+
288+
vals = arr(
289+
pointer(w.setdefault(10, c_short(10))),
290+
pointer(w.setdefault(11, c_short(11))),
291+
None,
292+
)
293+
gc.collect()
294+
295+
self.assertEqual(vals[0].contents.value, 10)
296+
self.assertEqual(vals[1].contents.value, 11)
297+
298+
vals[2] = vals[0]
299+
300+
self.assertEqual(vals[2].contents.value, 10)
301+
302+
vals[2][0] = w.setdefault(12, c_short(12))
303+
vals[2].contents = w.setdefault(13, c_short(13))
304+
305+
gc.collect()
306+
307+
self.assertEqual(vals[2].contents.value, 13)
308+
self.assertEqual(vals[0].contents.value, 12)
309+
282310

283311
if __name__ == '__main__':
284312
unittest.main()

0 commit comments

Comments
 (0)
0