Debian Codegraph @

Lib/test/test_ctypes/test_stringptr.py

raw
1 import sys
2 import unittest
3 from test import support
4 from ctypes import (CDLL, Structure, POINTER, create_string_buffer,
5 c_char, c_char_p)
6 from test.support import import_helper
7 _ctypes_test = import_helper.import_module("_ctypes_test")
8
9
10 lib = CDLL(_ctypes_test.__file__)
11
12
13 class StringPtrTestCase(unittest.TestCase):
14 @support.refcount_test
15 def test__POINTER_c_char(self):
16 class X(Structure):
17 _fields_ = [("str", POINTER(c_char))]
18 x = X()
19
20 # NULL pointer access
21 self.assertRaises(ValueError, getattr, x.str, "contents")
22 b = create_string_buffer(b"Hello, World")
23 orig_refcount = sys.getrefcount(b)
24 x.str = b
25 self.assertEqual(sys.getrefcount(b), orig_refcount + 1)
26
27 # POINTER(c_char) and Python string is NOT compatible
28 # POINTER(c_char) and create_string_buffer() is compatible
29 for i in range(len(b)):
30 self.assertEqual(b[i], x.str[i])
31
32 self.assertRaises(TypeError, setattr, x, "str", "Hello, World")
33
34 def test__c_char_p(self):
35 class X(Structure):
36 _fields_ = [("str", c_char_p)]
37 x = X()
38
39 # c_char_p and Python string is compatible
40 # c_char_p and create_string_buffer is NOT compatible
41 self.assertEqual(x.str, None)
42 x.str = b"Hello, World"
43 self.assertEqual(x.str, b"Hello, World")
44 b = create_string_buffer(b"Hello, World")
45 self.assertRaises(TypeError, setattr, x, b"str", b)
46
47
48 def test_functions(self):
49 strchr = lib.my_strchr
50 strchr.restype = c_char_p
51
52 # c_char_p and Python string is compatible
53 # c_char_p and create_string_buffer are now compatible
54 strchr.argtypes = c_char_p, c_char
55 self.assertEqual(strchr(b"abcdef", b"c"), b"cdef")
56 self.assertEqual(strchr(create_string_buffer(b"abcdef"), b"c"),
57 b"cdef")
58
59 # POINTER(c_char) and Python string is NOT compatible
60 # POINTER(c_char) and create_string_buffer() is compatible
61 strchr.argtypes = POINTER(c_char), c_char
62 buf = create_string_buffer(b"abcdef")
63 self.assertEqual(strchr(buf, b"c"), b"cdef")
64 self.assertEqual(strchr(b"abcdef", b"c"), b"cdef")
65
66 # XXX These calls are dangerous, because the first argument
67 # to strchr is no longer valid after the function returns!
68 # So we must keep a reference to buf separately
69
70 strchr.restype = POINTER(c_char)
71 buf = create_string_buffer(b"abcdef")
72 r = strchr(buf, b"c")
73 x = r[0], r[1], r[2], r[3], r[4]
74 self.assertEqual(x, (b"c", b"d", b"e", b"f", b"\000"))
75 del buf
76 # Because r is a pointer to memory that is freed after deleting buf,
77 # the pointer is hanging and using it would reference freed memory.
78
79
80 if __name__ == '__main__':
81 unittest.main()