Debian Codegraph @

extra_tests/ctypes_tests/test_pointers.py

raw symbols SCIP
1 import pytest
2 from ctypes import *
3 import struct
4
5 @pytest.mark.pypy_only
6 def test_get_ffi_argtype():
7 P = POINTER(c_int)
8 ffitype = P.get_ffi_argtype()
9 assert P.get_ffi_argtype() is ffitype
10 assert ffitype.deref_pointer() is c_int.get_ffi_argtype()
11
12 @pytest.mark.parametrize("c_type, py_type", [
13 (c_byte, int),
14 (c_ubyte, int),
15 (c_short, int),
16 (c_ushort, int),
17 (c_int, int),
18 (c_uint, int),
19 (c_long, int),
20 (c_ulong, int),
21 (c_longlong, int),
22 (c_ulonglong, int),
23 (c_double, float),
24 (c_float, float),
25 ])
26 def test_byref(c_type, py_type):
27 i = c_type(42)
28 p = byref(i)
29 assert type(p._obj) is c_type
30 assert p._obj.value == 42
31
32 def test_pointer_to_pointer():
33 x = c_int(32)
34 y = c_int(42)
35 p1 = pointer(x)
36 p2 = pointer(p1)
37 assert p2.contents.contents.value == 32
38 p2.contents.contents = y
39 assert p2.contents.contents.value == 42
40 assert p1.contents.value == 42
41
42 def test_c_char_p_byref(dll):
43 TwoOutArgs = dll.TwoOutArgs
44 TwoOutArgs.restype = None
45 TwoOutArgs.argtypes = [c_int, c_void_p, c_int, c_void_p]
46 a = c_int(3)
47 b = c_int(4)
48 c = c_int(5)
49 d = c_int(6)
50 TwoOutArgs(a, byref(b), c, byref(d))
51 assert b.value == 7
52 assert d.value == 11
53
54 def test_byref_cannot_be_bound():
55 class A(object):
56 _byref = byref
57 A._byref(c_int(5))
58
59 def test_byref_with_offset():
60 c = c_int()
61 d = byref(c)
62 base = cast(d, c_void_p).value
63 for i in [0, 1, 4, 1444, -10293]:
64 assert cast(byref(c, i), c_void_p).value == base + i
65
66 @pytest.mark.pypy_only
67 def test_issue2813_fix():
68 class C(Structure):
69 pass
70 POINTER(C)
71 C._fields_ = [('x', c_int)]
72 ffitype = C.get_ffi_argtype()
73 assert C.get_ffi_argtype() is ffitype
74 assert ffitype.sizeof() == sizeof(c_int)
75
76 @pytest.mark.pypy_only
77 def test_issue2813_cant_change_fields_after_get_ffi_argtype():
78 class C(Structure):
79 pass
80 ffitype = C.get_ffi_argtype()
81 with pytest.raises(NotImplementedError):
82 C._fields_ = [('x', c_int)]
83
84 def test_memoryview():
85 x = c_int(32)
86 p1 = pointer(x)
87 p2 = pointer(p1)
88
89 m1 = memoryview(p1)
90 assert struct.unpack('P', m1)[0] == addressof(x)
91 m2 = memoryview(p2)
92 assert struct.unpack('P', m2)[0] == addressof(p1)
93
94 def test_pointer_from_array():
95 A = c_ubyte * 4
96 a = A(19, 72, 0, 23)
97 P = POINTER(c_ubyte)
98 p = P(a)
99 for i in range(len(a)):
100 assert p[i] == a[i]