Debian Codegraph @

extra_tests/cffi_tests/test_c.py

raw symbols SCIP
1 import pytest
2 import sys
3
4 is_musl = False
5 if sys.platform == 'linux':
6 try:
7 from packaging.tags import platform_tags
8 is_musl = any(t.startswith('musllinux') for t in platform_tags())
9 del platform_tags
10 except ImportError:
11 pass
12
13 def _setup_path():
14 import os, sys
15 sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
16 _setup_path()
17 from _cffi_backend import *
18 from _cffi_backend import _get_types, _get_common_types
19 try:
20 from _cffi_backend import _testfunc
21 except ImportError:
22 def _testfunc(num):
23 pytest.skip("_testunc() not available")
24 from _cffi_backend import __version__
25
26 # ____________________________________________________________
27
28 import sys
29 import platform
30 import pytest
31 assert __version__ == "1.18.0.dev0", ("This test_c.py file is for testing a version"
32 " of cffi that differs from the one that we"
33 " get from 'import _cffi_backend'")
34
35 if sys.platform == "darwin" and platform.machine() == "arm64":
36 IS_MACOS_ARM64 = True
37 else:
38 IS_MACOS_ARM64 = False
39
40 if sys.version_info < (3,):
41 type_or_class = "type"
42 mandatory_b_prefix = ''
43 mandatory_u_prefix = 'u'
44 bytechr = chr
45 bitem2bchr = lambda x: x
46 class U(object):
47 def __add__(self, other):
48 return eval('u'+repr(other).replace(r'\\u', r'\u')
49 .replace(r'\\U', r'\U'))
50 u = U()
51 str2bytes = str
52 strict_compare = False
53 else:
54 type_or_class = "class"
55 long = int
56 unicode = str
57 unichr = chr
58 mandatory_b_prefix = 'b'
59 mandatory_u_prefix = ''
60 bytechr = lambda n: bytes([n])
61 bitem2bchr = bytechr
62 u = ""
63 str2bytes = lambda s: bytes(s, "ascii")
64 strict_compare = True
65
66 def size_of_int():
67 BInt = new_primitive_type("int")
68 return sizeof(BInt)
69
70 def size_of_long():
71 BLong = new_primitive_type("long")
72 return sizeof(BLong)
73
74 def size_of_ptr():
75 BInt = new_primitive_type("int")
76 BPtr = new_pointer_type(BInt)
77 return sizeof(BPtr)
78
79
80 def find_and_load_library(name, flags=RTLD_NOW):
81 import ctypes.util
82 if name is None:
83 path = None
84 else:
85 path = ctypes.util.find_library(name)
86 if path is None and sys.platform == 'darwin' and sys.version_info[:2] == (3, 8):
87 pytest.xfail("find_library usually broken on MacOS Python 3.8")
88 if path is None and name == 'c':
89 assert sys.platform == 'win32'
90 assert (sys.version_info >= (3,) or
91 '__pypy__' in sys.builtin_module_names)
92 pytest.skip("dlopen(None) cannot work on Windows "
93 "with PyPy or Python 3")
94 return load_library(path, flags)
95
96 def test_load_library():
97 x = find_and_load_library('c')
98 assert repr(x).startswith("<clibrary '")
99 x = find_and_load_library('c', RTLD_NOW | RTLD_GLOBAL)
100 assert repr(x).startswith("<clibrary '")
101 x = find_and_load_library('c', RTLD_LAZY)
102 assert repr(x).startswith("<clibrary '")
103
104 def test_all_rtld_symbols():
105 import sys
106 FFI_DEFAULT_ABI # these symbols must be defined
107 FFI_CDECL
108 RTLD_LAZY
109 RTLD_NOW
110 RTLD_GLOBAL
111 RTLD_LOCAL
112 if sys.platform.startswith("linux"):
113 RTLD_NODELETE
114 RTLD_NOLOAD
115 if not is_musl:
116 RTLD_DEEPBIND
117
118 def test_new_primitive_type():
119 pytest.raises(KeyError, new_primitive_type, "foo")
120 p = new_primitive_type("signed char")
121 assert repr(p) == "<ctype 'signed char'>"
122
123 def check_dir(p, expected):
124 got = [name for name in dir(p) if not name.startswith('_')]
125 assert got == sorted(expected)
126
127 def test_inspect_primitive_type():
128 p = new_primitive_type("signed char")
129 assert p.kind == "primitive"
130 assert p.cname == "signed char"
131 check_dir(p, ['cname', 'kind'])
132
133 def test_cast_to_signed_char():
134 p = new_primitive_type("signed char")
135 x = cast(p, -65 + 17*256)
136 assert repr(x) == "<cdata 'signed char' -65>"
137 assert repr(type(x)) == "<%s '_cffi_backend._CDataBase'>" % type_or_class
138 assert int(x) == -65
139 x = cast(p, -66 + (1<<199)*256)
140 assert repr(x) == "<cdata 'signed char' -66>"
141 assert int(x) == -66
142 assert (x == cast(p, -66)) is True
143 assert (x != cast(p, -66)) is False
144 q = new_primitive_type("short")
145 assert (x == cast(q, -66)) is True
146 assert (x != cast(q, -66)) is False
147
148 def test_sizeof_type():
149 pytest.raises(TypeError, sizeof, 42.5)
150 p = new_primitive_type("short")
151 assert sizeof(p) == 2
152
153 def test_integer_types():
154 for name in ['signed char', 'short', 'int', 'long', 'long long']:
155 p = new_primitive_type(name)
156 size = sizeof(p)
157 min = -(1 << (8*size-1))
158 max = (1 << (8*size-1)) - 1
159 assert int(cast(p, min)) == min
160 assert int(cast(p, max)) == max
161 assert int(cast(p, min - 1)) == max
162 assert int(cast(p, max + 1)) == min
163 pytest.raises(TypeError, cast, p, None)
164 assert long(cast(p, min - 1)) == max
165 assert int(cast(p, b'\x08')) == 8
166 assert int(cast(p, u+'\x08')) == 8
167 for name in ['char', 'short', 'int', 'long', 'long long']:
168 p = new_primitive_type('unsigned ' + name)
169 size = sizeof(p)
170 max = (1 << (8*size)) - 1
171 assert int(cast(p, 0)) == 0
172 assert int(cast(p, max)) == max
173 assert int(cast(p, -1)) == max
174 assert int(cast(p, max + 1)) == 0
175 assert long(cast(p, -1)) == max
176 assert int(cast(p, b'\xFE')) == 254
177 assert int(cast(p, u+'\xFE')) == 254
178
179 def test_no_float_on_int_types():
180 p = new_primitive_type('long')
181 pytest.raises(TypeError, float, cast(p, 42))
182 pytest.raises(TypeError, complex, cast(p, 42))
183
184 def test_float_types():
185 INF = 1E200 * 1E200
186 for name in ["float", "double"]:
187 p = new_primitive_type(name)
188 assert bool(cast(p, 0)) is False # since 1.7
189 assert bool(cast(p, -0.0)) is False # since 1.7
190 assert bool(cast(p, 1e-42)) is True
191 assert bool(cast(p, -1e-42)) is True
192 assert bool(cast(p, INF))
193 assert bool(cast(p, -INF))
194 assert bool(cast(p, float("nan")))
195 assert int(cast(p, -150)) == -150
196 assert int(cast(p, 61.91)) == 61
197 assert long(cast(p, 61.91)) == 61
198 assert type(int(cast(p, 61.91))) is int
199 assert type(int(cast(p, 1E22))) is long
200 assert type(long(cast(p, 61.91))) is long
201 assert type(long(cast(p, 1E22))) is long
202 pytest.raises(OverflowError, int, cast(p, INF))
203 pytest.raises(OverflowError, int, cast(p, -INF))
204 assert float(cast(p, 1.25)) == 1.25
205 assert float(cast(p, INF)) == INF
206 assert float(cast(p, -INF)) == -INF
207 if name == "float":
208 assert float(cast(p, 1.1)) != 1.1 # rounding error
209 assert float(cast(p, 1E200)) == INF # limited range
210
211 assert cast(p, -1.1) == cast(p, -1.1)
212 assert repr(float(cast(p, -0.0))) == '-0.0'
213 assert float(cast(p, b'\x09')) == 9.0
214 assert float(cast(p, u+'\x09')) == 9.0
215 assert float(cast(p, True)) == 1.0
216 pytest.raises(TypeError, cast, p, None)
217
218 def test_complex_types():
219 INF = 1E200 * 1E200
220 for name in ["float", "double"]:
221 p = new_primitive_type("_cffi_" + name + "_complex_t")
222 assert bool(cast(p, 0)) is False
223 assert bool(cast(p, INF))
224 assert bool(cast(p, -INF))
225 assert bool(cast(p, 0j)) is False
226 assert bool(cast(p, INF*1j))
227 assert bool(cast(p, -INF*1j))
228 # "can't convert complex to float", like CPython's "float(0j)"
229 pytest.raises(TypeError, int, cast(p, -150))
230 pytest.raises(TypeError, long, cast(p, -150))
231 pytest.raises(TypeError, float, cast(p, -150))
232 assert complex(cast(p, 1.25)) == 1.25
233 assert complex(cast(p, 1.25j)) == 1.25j
234 assert complex(cast(p, complex(0,INF))) == complex(0,INF)
235 assert complex(cast(p, -INF)) == -INF
236 if name == "float":
237 assert complex(cast(p, 1.1j)) != 1.1j # rounding error
238 assert complex(cast(p, 1E200+3j)) == INF+3j # limited range
239 assert complex(cast(p, complex(3,1E200))) == complex(3,INF) # limited range
240
241 assert cast(p, -1.1j) == cast(p, -1.1j)
242 assert repr(complex(cast(p, -0.0)).real) == '-0.0'
243 #assert repr(complex(cast(p, -0j))) == '-0j' # http://bugs.python.org/issue29602
244 assert complex(cast(p, b'\x09')) == 9.0 + 0j
245 assert complex(cast(p, u+'\x09')) == 9.0 + 0j
246 assert complex(cast(p, True)) == 1.0 + 0j
247 pytest.raises(TypeError, cast, p, None)
248 #
249 pytest.raises(TypeError, cast, new_primitive_type(name), 1+0j)
250 #
251 for basetype in ["char", "int", "uint64_t", "float",
252 "double", "long double"]:
253 baseobj = cast(new_primitive_type(basetype), 65)
254 pytest.raises(TypeError, complex, baseobj)
255 #
256 BArray = new_array_type(new_pointer_type(p), 10)
257 x = newp(BArray, None)
258 x[5] = 12.34 + 56.78j
259 assert type(x[5]) is complex
260 assert abs(x[5] - (12.34 + 56.78j)) < 1e-5
261 assert (x[5] == 12.34 + 56.78j) == (name == "double") # rounding error
262 #
263 class Foo:
264 def __complex__(self):
265 return 2 + 3j
266 assert complex(Foo()) == 2 + 3j
267 assert complex(cast(p, Foo())) == 2 + 3j
268 pytest.raises(TypeError, cast, new_primitive_type("int"), 1+0j)
269
270 def test_character_type():
271 p = new_primitive_type("char")
272 assert bool(cast(p, 'A')) is True
273 assert bool(cast(p, '\x00')) is False # since 1.7
274 assert cast(p, '\x00') == cast(p, -17*256)
275 assert int(cast(p, 'A')) == 65
276 assert long(cast(p, 'A')) == 65
277 assert type(int(cast(p, 'A'))) is int
278 assert type(long(cast(p, 'A'))) is long
279 assert str(cast(p, 'A')) == repr(cast(p, 'A'))
280 assert repr(cast(p, 'A')) == "<cdata 'char' %s'A'>" % mandatory_b_prefix
281 assert repr(cast(p, 255)) == r"<cdata 'char' %s'\xff'>" % mandatory_b_prefix
282 assert repr(cast(p, 0)) == r"<cdata 'char' %s'\x00'>" % mandatory_b_prefix
283
284 def test_pointer_type():
285 p = new_primitive_type("int")
286 assert repr(p) == "<ctype 'int'>"
287 p = new_pointer_type(p)
288 assert repr(p) == "<ctype 'int *'>"
289 p = new_pointer_type(p)
290 assert repr(p) == "<ctype 'int * *'>"
291 p = new_pointer_type(p)
292 assert repr(p) == "<ctype 'int * * *'>"
293
294 def test_inspect_pointer_type():
295 p1 = new_primitive_type("int")
296 p2 = new_pointer_type(p1)
297 assert p2.kind == "pointer"
298 assert p2.cname == "int *"
299 assert p2.item is p1
300 check_dir(p2, ['cname', 'kind', 'item'])
301 p3 = new_pointer_type(p2)
302 assert p3.item is p2
303
304 def test_pointer_to_int():
305 BInt = new_primitive_type("int")
306 pytest.raises(TypeError, newp, BInt)
307 pytest.raises(TypeError, newp, BInt, None)
308 BPtr = new_pointer_type(BInt)
309 p = newp(BPtr)
310 assert repr(p) == "<cdata 'int *' owning %d bytes>" % size_of_int()
311 p = newp(BPtr, None)
312 assert repr(p) == "<cdata 'int *' owning %d bytes>" % size_of_int()
313 p = newp(BPtr, 5000)
314 assert repr(p) == "<cdata 'int *' owning %d bytes>" % size_of_int()
315 q = cast(BPtr, p)
316 assert repr(q).startswith("<cdata 'int *' 0x")
317 assert p == q
318 assert hash(p) == hash(q)
319 e = pytest.raises(TypeError, newp, new_array_type(BPtr, None), None)
320 assert str(e.value) == (
321 "expected new array length or list/tuple/str, not NoneType")
322
323 def test_pointer_bool():
324 BInt = new_primitive_type("int")
325 BPtr = new_pointer_type(BInt)
326 p = cast(BPtr, 0)
327 assert bool(p) is False
328 p = cast(BPtr, 42)
329 assert bool(p) is True
330
331 def test_pointer_to_pointer():
332 BInt = new_primitive_type("int")
333 BPtr = new_pointer_type(BInt)
334 BPtrPtr = new_pointer_type(BPtr)
335 p = newp(BPtrPtr, None)
336 assert repr(p) == "<cdata 'int * *' owning %d bytes>" % size_of_ptr()
337
338 def test_reading_pointer_to_int():
339 BInt = new_primitive_type("int")
340 BPtr = new_pointer_type(BInt)
341 p = newp(BPtr, None)
342 assert p[0] == 0
343 p = newp(BPtr, 5000)
344 assert p[0] == 5000
345 with pytest.raises(IndexError):
346 p[1]
347 with pytest.raises(IndexError):
348 p[-1]
349
350 def test_reading_pointer_to_float():
351 BFloat = new_primitive_type("float")
352 pytest.raises(TypeError, newp, BFloat, None)
353 BPtr = new_pointer_type(BFloat)
354 p = newp(BPtr, None)
355 assert p[0] == 0.0 and type(p[0]) is float
356 p = newp(BPtr, 1.25)
357 assert p[0] == 1.25 and type(p[0]) is float
358 p = newp(BPtr, 1.1)
359 assert p[0] != 1.1 and abs(p[0] - 1.1) < 1E-5 # rounding errors
360
361 def test_cast_float_to_int():
362 for type in ["int", "unsigned int", "long", "unsigned long",
363 "long long", "unsigned long long"]:
364 p = new_primitive_type(type)
365 assert int(cast(p, 4.2)) == 4
366 pytest.raises(TypeError, newp, new_pointer_type(p), 4.2)
367
368 def test_newp_integer_types():
369 for name in ['signed char', 'short', 'int', 'long', 'long long']:
370 p = new_primitive_type(name)
371 pp = new_pointer_type(p)
372 size = sizeof(p)
373 min = -(1 << (8*size-1))
374 max = (1 << (8*size-1)) - 1
375 assert newp(pp, min)[0] == min
376 assert newp(pp, max)[0] == max
377 pytest.raises(OverflowError, newp, pp, min - 2 ** 32)
378 pytest.raises(OverflowError, newp, pp, min - 2 ** 64)
379 pytest.raises(OverflowError, newp, pp, max + 2 ** 32)
380 pytest.raises(OverflowError, newp, pp, max + 2 ** 64)
381 pytest.raises(OverflowError, newp, pp, min - 1)
382 pytest.raises(OverflowError, newp, pp, max + 1)
383 pytest.raises(OverflowError, newp, pp, min - 1 - 2 ** 32)
384 pytest.raises(OverflowError, newp, pp, min - 1 - 2 ** 64)
385 pytest.raises(OverflowError, newp, pp, max + 1)
386 pytest.raises(OverflowError, newp, pp, max + 1 + 2 ** 32)
387 pytest.raises(OverflowError, newp, pp, max + 1 + 2 ** 64)
388 pytest.raises(TypeError, newp, pp, 1.0)
389 for name in ['char', 'short', 'int', 'long', 'long long']:
390 p = new_primitive_type('unsigned ' + name)
391 pp = new_pointer_type(p)
392 size = sizeof(p)
393 max = (1 << (8*size)) - 1
394 assert newp(pp, 0)[0] == 0
395 assert newp(pp, max)[0] == max
396 pytest.raises(OverflowError, newp, pp, -1)
397 pytest.raises(OverflowError, newp, pp, max + 1)
398
399 def test_reading_pointer_to_char():
400 BChar = new_primitive_type("char")
401 pytest.raises(TypeError, newp, BChar, None)
402 BPtr = new_pointer_type(BChar)
403 p = newp(BPtr, None)
404 assert p[0] == b'\x00'
405 p = newp(BPtr, b'A')
406 assert p[0] == b'A'
407 pytest.raises(TypeError, newp, BPtr, 65)
408 pytest.raises(TypeError, newp, BPtr, b"foo")
409 pytest.raises(TypeError, newp, BPtr, u+"foo")
410 c = cast(BChar, b'A')
411 assert str(c) == repr(c)
412 assert int(c) == ord(b'A')
413 pytest.raises(TypeError, cast, BChar, b'foo')
414 pytest.raises(TypeError, cast, BChar, u+'foo')
415 e = pytest.raises(TypeError, newp, new_array_type(BPtr, None), 12.3)
416 assert str(e.value) == (
417 "expected new array length or list/tuple/str, not float")
418
419 def test_reading_pointer_to_pointer():
420 BVoidP = new_pointer_type(new_void_type())
421 BCharP = new_pointer_type(new_primitive_type("char"))
422 BInt = new_primitive_type("int")
423 BIntPtr = new_pointer_type(BInt)
424 BIntPtrPtr = new_pointer_type(BIntPtr)
425 q = newp(BIntPtr, 42)
426 assert q[0] == 42
427 p = newp(BIntPtrPtr, None)
428 assert p[0] is not None
429 assert p[0] == cast(BVoidP, 0)
430 assert p[0] == cast(BCharP, 0)
431 assert p[0] != None
432 assert repr(p[0]) == "<cdata 'int *' NULL>"
433 p[0] = q
434 assert p[0] != cast(BVoidP, 0)
435 assert p[0] != cast(BCharP, 0)
436 assert p[0][0] == 42
437 q[0] += 1
438 assert p[0][0] == 43
439 p = newp(BIntPtrPtr, q)
440 assert p[0][0] == 43
441
442 def test_load_standard_library():
443 if sys.platform == "win32":
444 pytest.raises(OSError, find_and_load_library, None)
445 return
446 x = find_and_load_library(None)
447 BVoidP = new_pointer_type(new_void_type())
448 assert x.load_function(BVoidP, 'strcpy')
449 pytest.raises(AttributeError, x.load_function,
450 BVoidP, 'xxx_this_function_does_not_exist')
451 # the next one is from 'libm', not 'libc', but we assume
452 # that it is already loaded too, so it should work
453 assert x.load_function(BVoidP, 'sqrt')
454 #
455 x.close_lib()
456 pytest.raises(ValueError, x.load_function, BVoidP, 'sqrt')
457 x.close_lib()
458
459 def test_no_len_on_nonarray():
460 p = new_primitive_type("int")
461 pytest.raises(TypeError, len, cast(p, 42))
462
463 def test_cmp_none():
464 p = new_primitive_type("int")
465 x = cast(p, 42)
466 assert (x == None) is False
467 assert (x != None) is True
468 assert (x == ["hello"]) is False
469 assert (x != ["hello"]) is True
470 y = cast(p, 0)
471 assert (y == None) is False
472
473 def test_invalid_indexing():
474 p = new_primitive_type("int")
475 x = cast(p, 42)
476 with pytest.raises(TypeError):
477 x[0]
478
479 def test_default_str():
480 BChar = new_primitive_type("char")
481 x = cast(BChar, 42)
482 assert str(x) == repr(x)
483 BInt = new_primitive_type("int")
484 x = cast(BInt, 42)
485 assert str(x) == repr(x)
486 BArray = new_array_type(new_pointer_type(BInt), 10)
487 x = newp(BArray, None)
488 assert str(x) == repr(x)
489
490 def test_default_unicode():
491 BInt = new_primitive_type("int")
492 x = cast(BInt, 42)
493 assert unicode(x) == unicode(repr(x))
494 BArray = new_array_type(new_pointer_type(BInt), 10)
495 x = newp(BArray, None)
496 assert unicode(x) == unicode(repr(x))
497
498 def test_cast_from_cdataint():
499 BInt = new_primitive_type("int")
500 x = cast(BInt, 0)
501 y = cast(new_pointer_type(BInt), x)
502 assert bool(y) is False
503 #
504 x = cast(BInt, 42)
505 y = cast(BInt, x)
506 assert int(y) == 42
507 y = cast(new_primitive_type("char"), x)
508 assert int(y) == 42
509 y = cast(new_primitive_type("float"), x)
510 assert float(y) == 42.0
511 #
512 z = cast(BInt, 42.5)
513 assert int(z) == 42
514 z = cast(BInt, y)
515 assert int(z) == 42
516
517 def test_void_type():
518 p = new_void_type()
519 assert p.kind == "void"
520 assert p.cname == "void"
521 check_dir(p, ['kind', 'cname'])
522
523 def test_array_type():
524 p = new_primitive_type("int")
525 assert repr(p) == "<ctype 'int'>"
526 #
527 pytest.raises(TypeError, new_array_type, new_pointer_type(p), "foo")
528 pytest.raises(ValueError, new_array_type, new_pointer_type(p), -42)
529 #
530 p1 = new_array_type(new_pointer_type(p), None)
531 assert repr(p1) == "<ctype 'int[]'>"
532 pytest.raises(ValueError, new_array_type, new_pointer_type(p1), 42)
533 #
534 p1 = new_array_type(new_pointer_type(p), 42)
535 p2 = new_array_type(new_pointer_type(p1), 25)
536 assert repr(p2) == "<ctype 'int[25][42]'>"
537 p2 = new_array_type(new_pointer_type(p1), None)
538 assert repr(p2) == "<ctype 'int[][42]'>"
539 #
540 pytest.raises(OverflowError,
541 new_array_type, new_pointer_type(p), sys.maxsize+1)
542 pytest.raises(OverflowError,
543 new_array_type, new_pointer_type(p), sys.maxsize // 3)
544
545 def test_inspect_array_type():
546 p = new_primitive_type("int")
547 p1 = new_array_type(new_pointer_type(p), None)
548 assert p1.kind == "array"
549 assert p1.cname == "int[]"
550 assert p1.item is p
551 assert p1.length is None
552 check_dir(p1, ['cname', 'kind', 'item', 'length'])
553 p1 = new_array_type(new_pointer_type(p), 42)
554 assert p1.kind == "array"
555 assert p1.cname == "int[42]"
556 assert p1.item is p
557 assert p1.length == 42
558 check_dir(p1, ['cname', 'kind', 'item', 'length'])
559
560 def test_array_instance():
561 LENGTH = 1423
562 p = new_primitive_type("int")
563 p1 = new_array_type(new_pointer_type(p), LENGTH)
564 a = newp(p1, None)
565 assert repr(a) == "<cdata 'int[%d]' owning %d bytes>" % (
566 LENGTH, LENGTH * size_of_int())
567 assert len(a) == LENGTH
568 for i in range(LENGTH):
569 assert a[i] == 0
570 with pytest.raises(IndexError):
571 a[LENGTH]
572 with pytest.raises(IndexError):
573 a[-1]
574 for i in range(LENGTH):
575 a[i] = i * i + 1
576 for i in range(LENGTH):
577 assert a[i] == i * i + 1
578 with pytest.raises(IndexError) as e:
579 a[LENGTH+100] = 500
580 assert ('(expected %d < %d)' % (LENGTH+100, LENGTH)) in str(e.value)
581 pytest.raises(TypeError, int, a)
582
583 def test_array_of_unknown_length_instance():
584 p = new_primitive_type("int")
585 p1 = new_array_type(new_pointer_type(p), None)
586 pytest.raises(TypeError, newp, p1, None)
587 pytest.raises(ValueError, newp, p1, -42)
588 a = newp(p1, 42)
589 assert len(a) == 42
590 for i in range(42):
591 a[i] -= i
592 for i in range(42):
593 assert a[i] == -i
594 with pytest.raises(IndexError):
595 a[42]
596 with pytest.raises(IndexError):
597 a[-1]
598 with pytest.raises(IndexError):
599 a[42] = 123
600 with pytest.raises(IndexError):
601 a[-1] = 456
602
603 def test_array_of_unknown_length_instance_with_initializer():
604 p = new_primitive_type("int")
605 p1 = new_array_type(new_pointer_type(p), None)
606 a = newp(p1, list(range(42)))
607 assert len(a) == 42
608 a = newp(p1, tuple(range(142)))
609 assert len(a) == 142
610
611 def test_array_initializer():
612 p = new_primitive_type("int")
613 p1 = new_array_type(new_pointer_type(p), None)
614 a = newp(p1, list(range(100, 142)))
615 for i in range(42):
616 assert a[i] == 100 + i
617 #
618 p2 = new_array_type(new_pointer_type(p), 43)
619 a = newp(p2, tuple(range(100, 142)))
620 for i in range(42):
621 assert a[i] == 100 + i
622 assert a[42] == 0 # extra uninitialized item
623
624 def test_array_add():
625 p = new_primitive_type("int")
626 p1 = new_array_type(new_pointer_type(p), 5) # int[5]
627 p2 = new_array_type(new_pointer_type(p1), 3) # int[3][5]
628 a = newp(p2, [list(range(n, n+5)) for n in [100, 200, 300]])
629 assert repr(a) == "<cdata 'int[3][5]' owning %d bytes>" % (
630 3*5*size_of_int(),)
631 assert repr(a + 0).startswith("<cdata 'int(*)[5]' 0x")
632 assert 0 + a == a + 0 != 1 + a == a + 1
633 assert repr(a[0]).startswith("<cdata 'int[5]' 0x")
634 assert repr((a + 0)[0]).startswith("<cdata 'int[5]' 0x")
635 assert repr(a[0] + 0).startswith("<cdata 'int *' 0x")
636 assert type(a[0][0]) is int
637 assert type((a[0] + 0)[0]) is int
638
639 def test_array_sub():
640 BInt = new_primitive_type("int")
641 BArray = new_array_type(new_pointer_type(BInt), 5) # int[5]
642 a = newp(BArray, None)
643 p = a + 1
644 assert p - a == 1
645 assert p - (a+0) == 1
646 assert a == (p - 1)
647 BPtr = new_pointer_type(new_primitive_type("short"))
648 q = newp(BPtr, None)
649 with pytest.raises(TypeError):
650 p - q
651 with pytest.raises(TypeError):
652 q - p
653 with pytest.raises(TypeError):
654 a - q
655 with pytest.raises(TypeError) as e:
656 q - a
657 assert str(e.value) == "cannot subtract cdata 'short *' and cdata 'int *'"
658
659 def test_ptr_sub_unaligned():
660 BInt = new_primitive_type("int")
661 BIntPtr = new_pointer_type(BInt)
662 a = cast(BIntPtr, 1240)
663 for bi in range(1430, 1438):
664 b = cast(BIntPtr, bi)
665 if ((bi - 1240) % size_of_int()) == 0:
666 assert b - a == (bi - 1240) // size_of_int()
667 assert a - b == (1240 - bi) // size_of_int()
668 else:
669 with pytest.raises(ValueError):
670 b - a
671 with pytest.raises(ValueError):
672 a - b
673
674 def test_cast_primitive_from_cdata():
675 p = new_primitive_type("int")
676 n = cast(p, cast(p, -42))
677 assert int(n) == -42
678 #
679 p = new_primitive_type("unsigned int")
680 n = cast(p, cast(p, 42))
681 assert int(n) == 42
682 #
683 p = new_primitive_type("long long")
684 n = cast(p, cast(p, -(1<<60)))
685 assert int(n) == -(1<<60)
686 #
687 p = new_primitive_type("unsigned long long")
688 n = cast(p, cast(p, 1<<63))
689 assert int(n) == 1<<63
690 #
691 p = new_primitive_type("float")
692 n = cast(p, cast(p, 42.5))
693 assert float(n) == 42.5
694 #
695 p = new_primitive_type("char")
696 n = cast(p, cast(p, "A"))
697 assert int(n) == ord("A")
698
699 def test_new_primitive_from_cdata():
700 p = new_primitive_type("int")
701 p1 = new_pointer_type(p)
702 n = newp(p1, cast(p, -42))
703 assert n[0] == -42
704 #
705 p = new_primitive_type("unsigned int")
706 p1 = new_pointer_type(p)
707 n = newp(p1, cast(p, 42))
708 assert n[0] == 42
709 #
710 p = new_primitive_type("float")
711 p1 = new_pointer_type(p)
712 n = newp(p1, cast(p, 42.5))
713 assert n[0] == 42.5
714 #
715 p = new_primitive_type("char")
716 p1 = new_pointer_type(p)
717 n = newp(p1, cast(p, "A"))
718 assert n[0] == b"A"
719
720 def test_cast_between_pointers():
721 BIntP = new_pointer_type(new_primitive_type("int"))
722 BIntA = new_array_type(BIntP, None)
723 a = newp(BIntA, [40, 41, 42, 43, 44])
724 BShortP = new_pointer_type(new_primitive_type("short"))
725 b = cast(BShortP, a)
726 c = cast(BIntP, b)
727 assert c[3] == 43
728 BLongLong = new_primitive_type("long long")
729 d = cast(BLongLong, c)
730 e = cast(BIntP, d)
731 assert e[3] == 43
732 f = cast(BIntP, int(d))
733 assert f[3] == 43
734 #
735 b = cast(BShortP, 0)
736 assert not b
737 c = cast(BIntP, b)
738 assert not c
739 assert int(cast(BLongLong, c)) == 0
740
741 def test_alignof():
742 BInt = new_primitive_type("int")
743 assert alignof(BInt) == sizeof(BInt)
744 BPtr = new_pointer_type(BInt)
745 assert alignof(BPtr) == sizeof(BPtr)
746 BArray = new_array_type(BPtr, None)
747 assert alignof(BArray) == alignof(BInt)
748
749 def test_new_struct_type():
750 BStruct = new_struct_type("foo")
751 assert repr(BStruct) == "<ctype 'foo'>"
752 BStruct = new_struct_type("struct foo")
753 assert repr(BStruct) == "<ctype 'struct foo'>"
754 BPtr = new_pointer_type(BStruct)
755 assert repr(BPtr) == "<ctype 'struct foo *'>"
756 pytest.raises(ValueError, sizeof, BStruct)
757 pytest.raises(ValueError, alignof, BStruct)
758
759 def test_new_union_type():
760 BUnion = new_union_type("union foo")
761 assert repr(BUnion) == "<ctype 'union foo'>"
762 BPtr = new_pointer_type(BUnion)
763 assert repr(BPtr) == "<ctype 'union foo *'>"
764
765 def test_complete_struct():
766 BLong = new_primitive_type("long")
767 BChar = new_primitive_type("char")
768 BShort = new_primitive_type("short")
769 BStruct = new_struct_type("struct foo")
770 assert BStruct.kind == "struct"
771 assert BStruct.cname == "struct foo"
772 assert BStruct.fields is None
773 check_dir(BStruct, ['cname', 'kind', 'fields'])
774 #
775 complete_struct_or_union(BStruct, [('a1', BLong, -1),
776 ('a2', BChar, -1),
777 ('a3', BShort, -1)])
778 d = BStruct.fields
779 assert len(d) == 3
780 assert d[0][0] == 'a1'
781 assert d[0][1].type is BLong
782 assert d[0][1].offset == 0
783 assert d[0][1].bitshift == -1
784 assert d[0][1].bitsize == -1
785 assert d[1][0] == 'a2'
786 assert d[1][1].type is BChar
787 assert d[1][1].offset == sizeof(BLong)
788 assert d[1][1].bitshift == -1
789 assert d[1][1].bitsize == -1
790 assert d[2][0] == 'a3'
791 assert d[2][1].type is BShort
792 assert d[2][1].offset == sizeof(BLong) + sizeof(BShort)
793 assert d[2][1].bitshift == -1
794 assert d[2][1].bitsize == -1
795 assert sizeof(BStruct) == 2 * sizeof(BLong)
796 assert alignof(BStruct) == alignof(BLong)
797
798 def test_complete_union():
799 BLong = new_primitive_type("long")
800 BChar = new_primitive_type("char")
801 BUnion = new_union_type("union foo")
802 assert BUnion.kind == "union"
803 assert BUnion.cname == "union foo"
804 assert BUnion.fields is None
805 complete_struct_or_union(BUnion, [('a1', BLong, -1),
806 ('a2', BChar, -1)])
807 d = BUnion.fields
808 assert len(d) == 2
809 assert d[0][0] == 'a1'
810 assert d[0][1].type is BLong
811 assert d[0][1].offset == 0
812 assert d[1][0] == 'a2'
813 assert d[1][1].type is BChar
814 assert d[1][1].offset == 0
815 assert sizeof(BUnion) == sizeof(BLong)
816 assert alignof(BUnion) == alignof(BLong)
817
818 def test_struct_instance():
819 BInt = new_primitive_type("int")
820 BStruct = new_struct_type("struct foo")
821 BStructPtr = new_pointer_type(BStruct)
822 p = cast(BStructPtr, 42)
823 with pytest.raises(AttributeError) as e:
824 p.a1 # opaque
825 assert str(e.value) == ("cdata 'struct foo *' points to an opaque type: "
826 "cannot read fields")
827 with pytest.raises(AttributeError) as e:
828 p.a1 = 10 # opaque
829 assert str(e.value) == ("cdata 'struct foo *' points to an opaque type: "
830 "cannot write fields")
831
832 complete_struct_or_union(BStruct, [('a1', BInt, -1),
833 ('a2', BInt, -1)])
834 p = newp(BStructPtr, None)
835 s = p[0]
836 assert s.a1 == 0
837 s.a2 = 123
838 assert s.a1 == 0
839 assert s.a2 == 123
840 with pytest.raises(OverflowError):
841 s.a1 = sys.maxsize+1
842 assert s.a1 == 0
843 with pytest.raises(AttributeError) as e:
844 p.foobar
845 assert str(e.value) == "cdata 'struct foo *' has no field 'foobar'"
846 with pytest.raises(AttributeError) as e:
847 p.foobar = 42
848 assert str(e.value) == "cdata 'struct foo *' has no field 'foobar'"
849 with pytest.raises(AttributeError) as e:
850 s.foobar
851 assert str(e.value) == "cdata 'struct foo' has no field 'foobar'"
852 with pytest.raises(AttributeError) as e:
853 s.foobar = 42
854 assert str(e.value) == "cdata 'struct foo' has no field 'foobar'"
855 j = cast(BInt, 42)
856 with pytest.raises(AttributeError) as e:
857 j.foobar
858 assert str(e.value) == "cdata 'int' has no attribute 'foobar'"
859 with pytest.raises(AttributeError) as e:
860 j.foobar = 42
861 assert str(e.value) == "cdata 'int' has no attribute 'foobar'"
862 j = cast(new_pointer_type(BInt), 42)
863 with pytest.raises(AttributeError) as e:
864 j.foobar
865 assert str(e.value) == "cdata 'int *' has no attribute 'foobar'"
866 with pytest.raises(AttributeError) as e:
867 j.foobar = 42
868 assert str(e.value) == "cdata 'int *' has no attribute 'foobar'"
869 pp = newp(new_pointer_type(BStructPtr), p)
870 with pytest.raises(AttributeError) as e:
871 pp.a1
872 assert str(e.value) == "cdata 'struct foo * *' has no attribute 'a1'"
873 with pytest.raises(AttributeError) as e:
874 pp.a1 = 42
875 assert str(e.value) == "cdata 'struct foo * *' has no attribute 'a1'"
876
877 def test_union_instance():
878 BInt = new_primitive_type("int")
879 BUInt = new_primitive_type("unsigned int")
880 BUnion = new_union_type("union bar")
881 complete_struct_or_union(BUnion, [('a1', BInt, -1), ('a2', BUInt, -1)])
882 p = newp(new_pointer_type(BUnion), [-42])
883 bigval = -42 + (1 << (8*size_of_int()))
884 assert p.a1 == -42
885 assert p.a2 == bigval
886 p = newp(new_pointer_type(BUnion), {'a2': bigval})
887 assert p.a1 == -42
888 assert p.a2 == bigval
889 pytest.raises(OverflowError, newp, new_pointer_type(BUnion),
890 {'a1': bigval})
891 p = newp(new_pointer_type(BUnion), [])
892 assert p.a1 == p.a2 == 0
893
894 def test_struct_pointer():
895 BInt = new_primitive_type("int")
896 BStruct = new_struct_type("struct foo")
897 BStructPtr = new_pointer_type(BStruct)
898 complete_struct_or_union(BStruct, [('a1', BInt, -1),
899 ('a2', BInt, -1)])
900 p = newp(BStructPtr, None)
901 assert p.a1 == 0 # read/write via the pointer (C equivalent: '->')
902 p.a2 = 123
903 assert p.a1 == 0
904 assert p.a2 == 123
905
906 def test_struct_init_list():
907 BVoidP = new_pointer_type(new_void_type())
908 BInt = new_primitive_type("int")
909 BIntPtr = new_pointer_type(BInt)
910 BStruct = new_struct_type("struct foo")
911 BStructPtr = new_pointer_type(BStruct)
912 complete_struct_or_union(BStruct, [('a1', BInt, -1),
913 ('a2', BInt, -1),
914 ('a3', BInt, -1),
915 ('p4', BIntPtr, -1)])
916 s = newp(BStructPtr, [123, 456])
917 assert s.a1 == 123
918 assert s.a2 == 456
919 assert s.a3 == 0
920 assert s.p4 == cast(BVoidP, 0)
921 assert s.p4 != 0
922 #
923 s = newp(BStructPtr, {'a2': 41122, 'a3': -123})
924 assert s.a1 == 0
925 assert s.a2 == 41122
926 assert s.a3 == -123
927 assert s.p4 == cast(BVoidP, 0)
928 #
929 pytest.raises(KeyError, newp, BStructPtr, {'foobar': 0})
930 #
931 p = newp(BIntPtr, 14141)
932 s = newp(BStructPtr, [12, 34, 56, p])
933 assert s.p4 == p
934 assert s.p4
935 #
936 s = newp(BStructPtr, [12, 34, 56, cast(BVoidP, 0)])
937 assert s.p4 == cast(BVoidP, 0)
938 assert not s.p4
939 #
940 pytest.raises(TypeError, newp, BStructPtr, [12, 34, 56, None])
941
942 def test_array_in_struct():
943 BInt = new_primitive_type("int")
944 BStruct = new_struct_type("struct foo")
945 BArrayInt5 = new_array_type(new_pointer_type(BInt), 5)
946 complete_struct_or_union(BStruct, [('a1', BArrayInt5, -1)])
947 s = newp(new_pointer_type(BStruct), [[20, 24, 27, 29, 30]])
948 assert s.a1[2] == 27
949 assert repr(s.a1).startswith("<cdata 'int[5]' 0x")
950
951 def test_offsetof():
952 def offsetof(BType, fieldname):
953 return typeoffsetof(BType, fieldname)[1]
954 BInt = new_primitive_type("int")
955 BStruct = new_struct_type("struct foo")
956 pytest.raises(TypeError, offsetof, BInt, "abc")
957 pytest.raises(TypeError, offsetof, BStruct, "abc")
958 complete_struct_or_union(BStruct, [('abc', BInt, -1), ('def', BInt, -1)])
959 assert offsetof(BStruct, 'abc') == 0
960 assert offsetof(BStruct, 'def') == size_of_int()
961 pytest.raises(KeyError, offsetof, BStruct, "ghi")
962 assert offsetof(new_pointer_type(BStruct), "def") == size_of_int()
963
964 def test_function_type():
965 BInt = new_primitive_type("int")
966 BFunc = new_function_type((BInt, BInt), BInt, False)
967 assert repr(BFunc) == "<ctype 'int(*)(int, int)'>"
968 BFunc2 = new_function_type((), BFunc, False)
969 assert repr(BFunc2) == "<ctype 'int(*(*)())(int, int)'>"
970
971 def test_inspect_function_type():
972 BInt = new_primitive_type("int")
973 BFunc = new_function_type((BInt, BInt), BInt, False)
974 assert BFunc.kind == "function"
975 assert BFunc.cname == "int(*)(int, int)"
976 assert BFunc.args == (BInt, BInt)
977 assert BFunc.result is BInt
978 assert BFunc.ellipsis is False
979 assert BFunc.abi == FFI_DEFAULT_ABI
980
981 def test_function_type_taking_struct():
982 BChar = new_primitive_type("char")
983 BShort = new_primitive_type("short")
984 BStruct = new_struct_type("struct foo")
985 complete_struct_or_union(BStruct, [('a1', BChar, -1),
986 ('a2', BShort, -1)])
987 BFunc = new_function_type((BStruct,), BShort, False)
988 assert repr(BFunc) == "<ctype 'short(*)(struct foo)'>"
989
990 def test_function_void_result():
991 BVoid = new_void_type()
992 BInt = new_primitive_type("int")
993 BFunc = new_function_type((BInt, BInt), BVoid, False)
994 assert repr(BFunc) == "<ctype 'void(*)(int, int)'>"
995
996 def test_function_void_arg():
997 BVoid = new_void_type()
998 BInt = new_primitive_type("int")
999 pytest.raises(TypeError, new_function_type, (BVoid,), BInt, False)
1000
1001 def test_call_function_0():
1002 BSignedChar = new_primitive_type("signed char")
1003 BFunc0 = new_function_type((BSignedChar, BSignedChar), BSignedChar, False)
1004 f = cast(BFunc0, _testfunc(0))
1005 assert f(40, 2) == 42
1006 assert f(-100, -100) == -200 + 256
1007 pytest.raises(OverflowError, f, 128, 0)
1008 pytest.raises(OverflowError, f, 0, 128)
1009
1010 def test_call_function_0_pretend_bool_result():
1011 BSignedChar = new_primitive_type("signed char")
1012 BBool = new_primitive_type("_Bool")
1013 BFunc0 = new_function_type((BSignedChar, BSignedChar), BBool, False)
1014 f = cast(BFunc0, _testfunc(0))
1015 assert f(40, -39) is True
1016 assert f(40, -40) is False
1017 pytest.raises(ValueError, f, 40, 2)
1018
1019 def test_call_function_1():
1020 BInt = new_primitive_type("int")
1021 BLong = new_primitive_type("long")
1022 BFunc1 = new_function_type((BInt, BLong), BLong, False)
1023 f = cast(BFunc1, _testfunc(1))
1024 assert f(40, 2) == 42
1025 assert f(-100, -100) == -200
1026 int_max = (1 << (8*size_of_int()-1)) - 1
1027 long_max = (1 << (8*size_of_long()-1)) - 1
1028 if int_max == long_max:
1029 assert f(int_max, 1) == - int_max - 1
1030 else:
1031 assert f(int_max, 1) == int_max + 1
1032
1033 def test_call_function_2():
1034 BLongLong = new_primitive_type("long long")
1035 BFunc2 = new_function_type((BLongLong, BLongLong), BLongLong, False)
1036 f = cast(BFunc2, _testfunc(2))
1037 longlong_max = (1 << (8*sizeof(BLongLong)-1)) - 1
1038 assert f(longlong_max - 42, 42) == longlong_max
1039 assert f(43, longlong_max - 42) == - longlong_max - 1
1040
1041 def test_call_function_3():
1042 BFloat = new_primitive_type("float")
1043 BDouble = new_primitive_type("double")
1044 BFunc3 = new_function_type((BFloat, BDouble), BDouble, False)
1045 f = cast(BFunc3, _testfunc(3))
1046 assert f(1.25, 5.1) == 1.25 + 5.1 # exact
1047 res = f(1.3, 5.1)
1048 assert res != 6.4 and abs(res - 6.4) < 1E-5 # inexact
1049
1050 def test_call_function_4():
1051 BFloat = new_primitive_type("float")
1052 BDouble = new_primitive_type("double")
1053 BFunc4 = new_function_type((BFloat, BDouble), BFloat, False)
1054 f = cast(BFunc4, _testfunc(4))
1055 res = f(1.25, 5.1)
1056 assert res != 6.35 and abs(res - 6.35) < 1E-5 # inexact
1057
1058 def test_call_function_5():
1059 BVoid = new_void_type()
1060 BFunc5 = new_function_type((), BVoid, False)
1061 f = cast(BFunc5, _testfunc(5))
1062 f() # did not crash
1063
1064 def test_call_function_6():
1065 BInt = new_primitive_type("int")
1066 BIntPtr = new_pointer_type(BInt)
1067 BFunc6 = new_function_type((BIntPtr,), BIntPtr, False)
1068 f = cast(BFunc6, _testfunc(6))
1069 x = newp(BIntPtr, 42)
1070 res = f(x)
1071 assert typeof(res) is BIntPtr
1072 assert res[0] == 42 - 1000
1073 #
1074 BIntArray = new_array_type(BIntPtr, None)
1075 BFunc6bis = new_function_type((BIntArray,), BIntPtr, False)
1076 f = cast(BFunc6bis, _testfunc(6))
1077 #
1078 res = f([142])
1079 assert typeof(res) is BIntPtr
1080 assert res[0] == 142 - 1000
1081 #
1082 res = f((143,))
1083 assert typeof(res) is BIntPtr
1084 assert res[0] == 143 - 1000
1085 #
1086 x = newp(BIntArray, [242])
1087 res = f(x)
1088 assert typeof(res) is BIntPtr
1089 assert res[0] == 242 - 1000
1090 #
1091 pytest.raises(TypeError, f, 123456)
1092 pytest.raises(TypeError, f, "foo")
1093 pytest.raises(TypeError, f, u+"bar")
1094
1095 def test_call_function_7():
1096 BChar = new_primitive_type("char")
1097 BShort = new_primitive_type("short")
1098 BStruct = new_struct_type("struct foo")
1099 BStructPtr = new_pointer_type(BStruct)
1100 complete_struct_or_union(BStruct, [('a1', BChar, -1),
1101 ('a2', BShort, -1)])
1102 BFunc7 = new_function_type((BStruct,), BShort, False)
1103 f = cast(BFunc7, _testfunc(7))
1104 res = f({'a1': b'A', 'a2': -4042})
1105 assert res == -4042 + ord(b'A')
1106 #
1107 x = newp(BStructPtr, {'a1': b'A', 'a2': -4042})
1108 res = f(x[0])
1109 assert res == -4042 + ord(b'A')
1110
1111 def test_call_function_20():
1112 BChar = new_primitive_type("char")
1113 BShort = new_primitive_type("short")
1114 BStruct = new_struct_type("struct foo")
1115 BStructPtr = new_pointer_type(BStruct)
1116 complete_struct_or_union(BStruct, [('a1', BChar, -1),
1117 ('a2', BShort, -1)])
1118 BFunc20 = new_function_type((BStructPtr,), BShort, False)
1119 f = cast(BFunc20, _testfunc(20))
1120 x = newp(BStructPtr, {'a1': b'A', 'a2': -4042})
1121 # can't pass a 'struct foo'
1122 pytest.raises(TypeError, f, x[0])
1123
1124 def test_call_function_21():
1125 BInt = new_primitive_type("int")
1126 BStruct = new_struct_type("struct foo")
1127 complete_struct_or_union(BStruct, [('a', BInt, -1),
1128 ('b', BInt, -1),
1129 ('c', BInt, -1),
1130 ('d', BInt, -1),
1131 ('e', BInt, -1),
1132 ('f', BInt, -1),
1133 ('g', BInt, -1),
1134 ('h', BInt, -1),
1135 ('i', BInt, -1),
1136 ('j', BInt, -1)])
1137 BFunc21 = new_function_type((BStruct,), BInt, False)
1138 f = cast(BFunc21, _testfunc(21))
1139 res = f(list(range(13, 3, -1)))
1140 lst = [(n << i) for (i, n) in enumerate(range(13, 3, -1))]
1141 assert res == sum(lst)
1142
1143 def test_call_function_22():
1144 BInt = new_primitive_type("int")
1145 BArray10 = new_array_type(new_pointer_type(BInt), 10)
1146 BStruct = new_struct_type("struct foo")
1147 BStructP = new_pointer_type(BStruct)
1148 complete_struct_or_union(BStruct, [('a', BArray10, -1)])
1149 BFunc22 = new_function_type((BStruct, BStruct), BStruct, False)
1150 f = cast(BFunc22, _testfunc(22))
1151 p1 = newp(BStructP, {'a': list(range(100, 110))})
1152 p2 = newp(BStructP, {'a': list(range(1000, 1100, 10))})
1153 res = f(p1[0], p2[0])
1154 for i in range(10):
1155 assert res.a[i] == p1.a[i] - p2.a[i]
1156
1157 def test_call_function_23():
1158 BVoid = new_void_type() # declaring the function as int(void*)
1159 BVoidP = new_pointer_type(BVoid)
1160 BInt = new_primitive_type("int")
1161 BFunc23 = new_function_type((BVoidP,), BInt, False)
1162 f = cast(BFunc23, _testfunc(23))
1163 res = f(b"foo")
1164 assert res == 1000 * ord(b'f')
1165 res = f(cast(BVoidP, 0)) # NULL
1166 assert res == -42
1167 pytest.raises(TypeError, f, None)
1168 pytest.raises(TypeError, f, 0)
1169 pytest.raises(TypeError, f, 0.0)
1170
1171 def test_call_function_23_bis():
1172 # declaring the function as int(unsigned char*)
1173 BUChar = new_primitive_type("unsigned char")
1174 BUCharP = new_pointer_type(BUChar)
1175 BInt = new_primitive_type("int")
1176 BFunc23 = new_function_type((BUCharP,), BInt, False)
1177 f = cast(BFunc23, _testfunc(23))
1178 res = f(b"foo")
1179 assert res == 1000 * ord(b'f')
1180
1181 def test_call_function_23_bool_array():
1182 # declaring the function as int(_Bool*)
1183 BBool = new_primitive_type("_Bool")
1184 BBoolP = new_pointer_type(BBool)
1185 BInt = new_primitive_type("int")
1186 BFunc23 = new_function_type((BBoolP,), BInt, False)
1187 f = cast(BFunc23, _testfunc(23))
1188 res = f(b"\x01\x01")
1189 assert res == 1000
1190 pytest.raises(ValueError, f, b"\x02\x02")
1191
1192 def test_cannot_pass_struct_with_array_of_length_0():
1193 BInt = new_primitive_type("int")
1194 BArray0 = new_array_type(new_pointer_type(BInt), 0)
1195 BStruct = new_struct_type("struct foo")
1196 BStructP = new_pointer_type(BStruct)
1197 complete_struct_or_union(BStruct, [('a', BArray0)])
1198 BFunc = new_function_type((BStruct,), BInt, False)
1199 pytest.raises(NotImplementedError, cast(BFunc, 123), cast(BStructP, 123))
1200 BFunc2 = new_function_type((BInt,), BStruct, False)
1201 pytest.raises(NotImplementedError, cast(BFunc2, 123), 123)
1202
1203 pytest.mark.skipif(IS_MACOS_ARM64, reason="vararg not supported")
1204 def test_call_function_9():
1205 if not sys.platform.startswith("linux"):
1206 pytest.skip("untested")
1207 BInt = new_primitive_type("int")
1208 BFunc9 = new_function_type((BInt,), BInt, True) # vararg
1209 f = cast(BFunc9, _testfunc(9))
1210 assert f(0) == 0
1211 assert f(1, cast(BInt, 42)) == 42
1212 assert f(2, cast(BInt, 40), cast(BInt, 2)) == 42
1213 pytest.raises(TypeError, f, 1, 42)
1214 pytest.raises(TypeError, f, 2, None)
1215 # promotion of chars and shorts to ints
1216 BSChar = new_primitive_type("signed char")
1217 BUChar = new_primitive_type("unsigned char")
1218 BSShort = new_primitive_type("short")
1219 assert f(3, cast(BSChar, -3), cast(BUChar, 200), cast(BSShort, -5)) == 192
1220
1221 def test_call_function_24():
1222 BFloat = new_primitive_type("float")
1223 BFloatComplex = new_primitive_type("_cffi_float_complex_t")
1224 BFunc3 = new_function_type((BFloat, BFloat), BFloatComplex, False)
1225 if 0: # libffi returning nonsense silently, so logic disabled for now
1226 f = cast(BFunc3, _testfunc(24))
1227 result = f(1.25, 5.1)
1228 assert type(result) == complex
1229 assert result.real == 1.25 # exact
1230 assert (result.imag != 2*5.1) and (abs(result.imag - 2*5.1) < 1e-5) # inexact
1231 else:
1232 f = cast(BFunc3, _testfunc(9))
1233 pytest.raises(NotImplementedError, f, 12.3, 34.5)
1234
1235 def test_call_function_25():
1236 BDouble = new_primitive_type("double")
1237 BDoubleComplex = new_primitive_type("_cffi_double_complex_t")
1238 BFunc3 = new_function_type((BDouble, BDouble), BDoubleComplex, False)
1239 if 0: # libffi returning nonsense silently, so logic disabled for now
1240 f = cast(BFunc3, _testfunc(25))
1241 result = f(1.25, 5.1)
1242 assert type(result) == complex
1243 assert result.real == 1.25 # exact
1244 assert (result.imag != 2*5.1) and (abs(result.imag - 2*5.1) < 1e-10) # inexact
1245 else:
1246 f = cast(BFunc3, _testfunc(9))
1247 pytest.raises(NotImplementedError, f, 12.3, 34.5)
1248
1249 def test_cannot_call_with_a_autocompleted_struct():
1250 BSChar = new_primitive_type("signed char")
1251 BDouble = new_primitive_type("double")
1252 BStruct = new_struct_type("struct foo")
1253 BStructPtr = new_pointer_type(BStruct)
1254 complete_struct_or_union(BStruct, [('c', BDouble, -1, 8),
1255 ('a', BSChar, -1, 2),
1256 ('b', BSChar, -1, 0)])
1257 BFunc = new_function_type((BStruct,), BDouble) # internally not callable
1258 dummy_func = cast(BFunc, 42)
1259 e = pytest.raises(NotImplementedError, dummy_func, "?")
1260 msg = ("ctype 'struct foo' not supported as argument. It is a struct "
1261 'declared with "...;", but the C calling convention may depend '
1262 "on the missing fields; or, it contains anonymous struct/unions. "
1263 "Such structs are only supported as argument if the function is "
1264 "'API mode' and non-variadic (i.e. declared inside ffibuilder."
1265 "cdef()+ffibuilder.set_source() and not taking a final '...' "
1266 "argument)")
1267 assert str(e.value) == msg
1268
1269 def test_new_charp():
1270 BChar = new_primitive_type("char")
1271 BCharP = new_pointer_type(BChar)
1272 BCharA = new_array_type(BCharP, None)
1273 x = newp(BCharA, 42)
1274 assert len(x) == 42
1275 x = newp(BCharA, b"foobar")
1276 assert len(x) == 7
1277
1278 def test_load_and_call_function():
1279 BChar = new_primitive_type("char")
1280 BCharP = new_pointer_type(BChar)
1281 BLong = new_primitive_type("long")
1282 BFunc = new_function_type((BCharP,), BLong, False)
1283 ll = find_and_load_library('c')
1284 strlen = ll.load_function(BFunc, "strlen")
1285 input = newp(new_array_type(BCharP, None), b"foobar")
1286 assert strlen(input) == 6
1287 #
1288 assert strlen(b"foobarbaz") == 9
1289 #
1290 BVoidP = new_pointer_type(new_void_type())
1291 strlenaddr = ll.load_function(BVoidP, "strlen")
1292 assert strlenaddr == cast(BVoidP, strlen)
1293
1294 def test_read_variable():
1295 ## FIXME: this test assumes glibc specific behavior, it's not compliant with C standard
1296 ## https://bugs.pypy.org/issue1643
1297 if not sys.platform.startswith("linux"):
1298 pytest.skip("untested")
1299 BVoidP = new_pointer_type(new_void_type())
1300 ll = find_and_load_library('c')
1301 stderr = ll.read_variable(BVoidP, "stderr")
1302 assert stderr == cast(BVoidP, _testfunc(8))
1303 #
1304 ll.close_lib()
1305 pytest.raises(ValueError, ll.read_variable, BVoidP, "stderr")
1306
1307 def test_read_variable_as_unknown_length_array():
1308 ## FIXME: this test assumes glibc specific behavior, it's not compliant with C standard
1309 ## https://bugs.pypy.org/issue1643
1310 if not sys.platform.startswith("linux"):
1311 pytest.skip("untested")
1312 BCharP = new_pointer_type(new_primitive_type("char"))
1313 BArray = new_array_type(BCharP, None)
1314 ll = find_and_load_library('c')
1315 stderr = ll.read_variable(BArray, "stderr")
1316 assert repr(stderr).startswith("<cdata 'char *' 0x")
1317 # ^^ and not 'char[]', which is basically not allowed and would crash
1318
1319 def test_write_variable():
1320 ## FIXME: this test assumes glibc specific behavior, it's not compliant with C standard
1321 ## https://bugs.pypy.org/issue1643
1322 if not sys.platform.startswith("linux") or is_musl:
1323 pytest.skip("untested")
1324 BVoidP = new_pointer_type(new_void_type())
1325 ll = find_and_load_library('c')
1326 stderr = ll.read_variable(BVoidP, "stderr")
1327 ll.write_variable(BVoidP, "stderr", cast(BVoidP, 0))
1328 assert ll.read_variable(BVoidP, "stderr") is not None
1329 assert not ll.read_variable(BVoidP, "stderr")
1330 ll.write_variable(BVoidP, "stderr", stderr)
1331 assert ll.read_variable(BVoidP, "stderr") == stderr
1332 #
1333 ll.close_lib()
1334 pytest.raises(ValueError, ll.write_variable, BVoidP, "stderr", stderr)
1335
1336
1337 def test_callback():
1338 BInt = new_primitive_type("int")
1339 def make_callback():
1340 def cb(n):
1341 return n + 1
1342 BFunc = new_function_type((BInt,), BInt, False)
1343 return callback(BFunc, cb, 42) # 'cb' and 'BFunc' go out of scope
1344 f = make_callback()
1345 assert f(-142) == -141
1346 assert repr(f).startswith(
1347 "<cdata 'int(*)(int)' calling <function ")
1348 assert "cb at 0x" in repr(f)
1349 e = pytest.raises(TypeError, f)
1350 assert str(e.value) == "'int(*)(int)' expects 1 arguments, got 0"
1351
1352
1353 def test_callback_exception():
1354 pytest.skip("XXX not written for Python 2")
1355 def check_value(x):
1356 if x == 10000:
1357 raise ValueError(42)
1358 def Zcb1(x):
1359 check_value(x)
1360 return x * 3
1361 BShort = new_primitive_type("short")
1362 BFunc = new_function_type((BShort,), BShort, False)
1363
1364 f = callback(BFunc, Zcb1, -42)
1365 seen = []
1366 oops_result = None
1367 def oops(*args):
1368 seen.append(args)
1369 return oops_result
1370 ff = callback(BFunc, Zcb1, -42, oops)
1371 with _assert_unraisable(None):
1372 assert f(100) == 300
1373 with _assert_unraisable(ValueError, '42', ['in Zcb1', 'in check_value']):
1374 assert f(10000) == -42
1375
1376 bigvalue = 20000
1377 with _assert_unraisable(OverflowError, "integer 60000 does not fit 'short'", ['callback', 'Zcb1']):
1378 assert f(bigvalue) == -42
1379 assert len(seen) == 0
1380
1381 with _assert_unraisable(None):
1382 assert ff(bigvalue) == -42
1383 assert len(seen) == 1
1384 exc, val, tb = seen[0]
1385 assert exc is OverflowError
1386 assert str(val) == "integer 60000 does not fit 'short'"
1387
1388 del seen[:]
1389 oops_result = 81
1390 with _assert_unraisable(None):
1391 assert ff(bigvalue) == 81
1392
1393 assert len(seen) == 1
1394 exc, val, tb = seen[0]
1395 assert exc is OverflowError
1396 assert str(val) == "integer 60000 does not fit 'short'"
1397
1398 del seen[:]
1399 oops_result = "xy" # not None and not an int!
1400
1401 with _assert_unraisable(TypeError, "an integer is required", ["integer 60000 does not fit 'short'"]):
1402 assert ff(bigvalue) == -42
1403
1404 seen = "not a list" # this makes the oops() function crash
1405 oops_result = None
1406 with _assert_unraisable(AttributeError, "'str' object has no attribute 'append", ['Zcb1', 'ff', 'oops']):
1407 assert ff(bigvalue) == -42
1408
1409
1410 def test_callback_return_type():
1411 for rettype in ["signed char", "short", "int", "long", "long long",
1412 "unsigned char", "unsigned short", "unsigned int",
1413 "unsigned long", "unsigned long long"]:
1414 BRet = new_primitive_type(rettype)
1415 def cb(n):
1416 return n + 1
1417 BFunc = new_function_type((BRet,), BRet)
1418 f = callback(BFunc, cb, 42)
1419 assert f(41) == 42
1420 if rettype.startswith("unsigned "):
1421 min = 0
1422 max = (1 << (8*sizeof(BRet))) - 1
1423 else:
1424 min = -(1 << (8*sizeof(BRet)-1))
1425 max = (1 << (8*sizeof(BRet)-1)) - 1
1426 assert f(min) == min + 1
1427 assert f(max - 1) == max
1428 assert f(max) == 42
1429
1430 def test_a_lot_of_callbacks():
1431 BIGNUM = 10000
1432 if 'PY_DOT_PY' in globals(): BIGNUM = 100 # tests on py.py
1433 #
1434 BInt = new_primitive_type("int")
1435 BFunc = new_function_type((BInt,), BInt, False)
1436 def make_callback(m):
1437 def cb(n):
1438 return n + m
1439 return callback(BFunc, cb, 42) # 'cb' goes out of scope
1440 #
1441 flist = [make_callback(i) for i in range(BIGNUM)]
1442 for i, f in enumerate(flist):
1443 assert f(-142) == -142 + i
1444
1445 def test_callback_receiving_tiny_struct():
1446 BSChar = new_primitive_type("signed char")
1447 BInt = new_primitive_type("int")
1448 BStruct = new_struct_type("struct foo")
1449 BStructPtr = new_pointer_type(BStruct)
1450 complete_struct_or_union(BStruct, [('a', BSChar, -1),
1451 ('b', BSChar, -1)])
1452 def cb(s):
1453 return s.a + 10 * s.b
1454 BFunc = new_function_type((BStruct,), BInt)
1455 f = callback(BFunc, cb)
1456 p = newp(BStructPtr, [-2, -4])
1457 n = f(p[0])
1458 assert n == -42
1459
1460 def test_callback_returning_tiny_struct():
1461 BSChar = new_primitive_type("signed char")
1462 BInt = new_primitive_type("int")
1463 BStruct = new_struct_type("struct foo")
1464 BStructPtr = new_pointer_type(BStruct)
1465 complete_struct_or_union(BStruct, [('a', BSChar, -1),
1466 ('b', BSChar, -1)])
1467 def cb(n):
1468 return newp(BStructPtr, [-n, -3*n])[0]
1469 BFunc = new_function_type((BInt,), BStruct)
1470 f = callback(BFunc, cb)
1471 s = f(10)
1472 assert typeof(s) is BStruct
1473 assert repr(s) == "<cdata 'struct foo' owning 2 bytes>"
1474 assert s.a == -10
1475 assert s.b == -30
1476
1477 def test_callback_receiving_struct():
1478 BSChar = new_primitive_type("signed char")
1479 BInt = new_primitive_type("int")
1480 BDouble = new_primitive_type("double")
1481 BStruct = new_struct_type("struct foo")
1482 BStructPtr = new_pointer_type(BStruct)
1483 complete_struct_or_union(BStruct, [('a', BSChar, -1),
1484 ('b', BDouble, -1)])
1485 def cb(s):
1486 return s.a + int(s.b)
1487 BFunc = new_function_type((BStruct,), BInt)
1488 f = callback(BFunc, cb)
1489 p = newp(BStructPtr, [-2, 44.444])
1490 n = f(p[0])
1491 assert n == 42
1492
1493 def test_callback_returning_struct():
1494 BSChar = new_primitive_type("signed char")
1495 BInt = new_primitive_type("int")
1496 BDouble = new_primitive_type("double")
1497 BStruct = new_struct_type("struct foo")
1498 BStructPtr = new_pointer_type(BStruct)
1499 complete_struct_or_union(BStruct, [('a', BSChar, -1),
1500 ('b', BDouble, -1)])
1501 def cb(n):
1502 return newp(BStructPtr, [-n, 1E-42])[0]
1503 BFunc = new_function_type((BInt,), BStruct)
1504 f = callback(BFunc, cb)
1505 s = f(10)
1506 assert typeof(s) is BStruct
1507 assert repr(s) in ["<cdata 'struct foo' owning 12 bytes>",
1508 "<cdata 'struct foo' owning 16 bytes>"]
1509 assert s.a == -10
1510 assert s.b == 1E-42
1511
1512 def test_callback_receiving_big_struct():
1513 BInt = new_primitive_type("int")
1514 BStruct = new_struct_type("struct foo")
1515 BStructPtr = new_pointer_type(BStruct)
1516 complete_struct_or_union(BStruct, [('a', BInt, -1),
1517 ('b', BInt, -1),
1518 ('c', BInt, -1),
1519 ('d', BInt, -1),
1520 ('e', BInt, -1),
1521 ('f', BInt, -1),
1522 ('g', BInt, -1),
1523 ('h', BInt, -1),
1524 ('i', BInt, -1),
1525 ('j', BInt, -1)])
1526 def cb(s):
1527 for i, name in enumerate("abcdefghij"):
1528 assert getattr(s, name) == 13 - i
1529 return 42
1530 BFunc = new_function_type((BStruct,), BInt)
1531 f = callback(BFunc, cb)
1532 p = newp(BStructPtr, list(range(13, 3, -1)))
1533 n = f(p[0])
1534 assert n == 42
1535
1536 def test_callback_returning_big_struct():
1537 BInt = new_primitive_type("int")
1538 BStruct = new_struct_type("struct foo")
1539 BStructPtr = new_pointer_type(BStruct)
1540 complete_struct_or_union(BStruct, [('a', BInt, -1),
1541 ('b', BInt, -1),
1542 ('c', BInt, -1),
1543 ('d', BInt, -1),
1544 ('e', BInt, -1),
1545 ('f', BInt, -1),
1546 ('g', BInt, -1),
1547 ('h', BInt, -1),
1548 ('i', BInt, -1),
1549 ('j', BInt, -1)])
1550 def cb():
1551 return newp(BStructPtr, list(range(13, 3, -1)))[0]
1552 BFunc = new_function_type((), BStruct)
1553 f = callback(BFunc, cb)
1554 s = f()
1555 assert typeof(s) is BStruct
1556 assert repr(s) in ["<cdata 'struct foo' owning 40 bytes>",
1557 "<cdata 'struct foo' owning 80 bytes>"]
1558 for i, name in enumerate("abcdefghij"):
1559 assert getattr(s, name) == 13 - i
1560
1561 def test_callback_returning_void():
1562 BVoid = new_void_type()
1563 BFunc = new_function_type((), BVoid, False)
1564 def cb():
1565 seen.append(42)
1566 f = callback(BFunc, cb)
1567 seen = []
1568 f()
1569 assert seen == [42]
1570 pytest.raises(TypeError, callback, BFunc, cb, -42)
1571
1572 def test_enum_type():
1573 BUInt = new_primitive_type("unsigned int")
1574 BEnum = new_enum_type("foo", (), (), BUInt)
1575 assert repr(BEnum) == "<ctype 'foo'>"
1576 assert BEnum.kind == "enum"
1577 assert BEnum.cname == "foo"
1578 assert BEnum.elements == {}
1579 #
1580 BInt = new_primitive_type("int")
1581 BEnum = new_enum_type("enum foo", ('def', 'c', 'ab'), (0, 1, -20), BInt)
1582 assert BEnum.kind == "enum"
1583 assert BEnum.cname == "enum foo"
1584 assert BEnum.elements == {-20: 'ab', 0: 'def', 1: 'c'}
1585 # 'elements' is not the real dict, but merely a copy
1586 BEnum.elements[2] = '??'
1587 assert BEnum.elements == {-20: 'ab', 0: 'def', 1: 'c'}
1588 #
1589 BEnum = new_enum_type("enum bar", ('ab', 'cd'), (5, 5), BUInt)
1590 assert BEnum.elements == {5: 'ab'}
1591 assert BEnum.relements == {'ab': 5, 'cd': 5}
1592
1593 def test_cast_to_enum():
1594 BInt = new_primitive_type("int")
1595 BEnum = new_enum_type("enum foo", ('def', 'c', 'ab'), (0, 1, -20), BInt)
1596 assert sizeof(BEnum) == sizeof(BInt)
1597 e = cast(BEnum, 0)
1598 assert repr(e) == "<cdata 'enum foo' 0: def>"
1599 assert repr(cast(BEnum, -42)) == "<cdata 'enum foo' -42>"
1600 assert repr(cast(BEnum, -20)) == "<cdata 'enum foo' -20: ab>"
1601 assert string(e) == 'def'
1602 assert string(cast(BEnum, -20)) == 'ab'
1603 assert int(cast(BEnum, 1)) == 1
1604 assert int(cast(BEnum, 0)) == 0
1605 assert int(cast(BEnum, -242 + 2**128)) == -242
1606 assert string(cast(BEnum, -242 + 2**128)) == '-242'
1607 #
1608 BUInt = new_primitive_type("unsigned int")
1609 BEnum = new_enum_type("enum bar", ('def', 'c', 'ab'), (0, 1, 20), BUInt)
1610 e = cast(BEnum, -1)
1611 assert repr(e) == "<cdata 'enum bar' 4294967295>" # unsigned int
1612 #
1613 BLong = new_primitive_type("long")
1614 BEnum = new_enum_type("enum baz", (), (), BLong)
1615 assert sizeof(BEnum) == sizeof(BLong)
1616 e = cast(BEnum, -1)
1617 assert repr(e) == "<cdata 'enum baz' -1>"
1618
1619 def test_enum_with_non_injective_mapping():
1620 BInt = new_primitive_type("int")
1621 BEnum = new_enum_type("enum foo", ('ab', 'cd'), (7, 7), BInt)
1622 e = cast(BEnum, 7)
1623 assert repr(e) == "<cdata 'enum foo' 7: ab>"
1624 assert string(e) == 'ab'
1625
1626 def test_enum_in_struct():
1627 BInt = new_primitive_type("int")
1628 BEnum = new_enum_type("enum foo", ('def', 'c', 'ab'), (0, 1, -20), BInt)
1629 BStruct = new_struct_type("struct bar")
1630 BStructPtr = new_pointer_type(BStruct)
1631 complete_struct_or_union(BStruct, [('a1', BEnum, -1)])
1632 p = newp(BStructPtr, [-20])
1633 assert p.a1 == -20
1634 p = newp(BStructPtr, [12])
1635 assert p.a1 == 12
1636 e = pytest.raises(TypeError, newp, BStructPtr, [None])
1637 msg = str(e.value)
1638 assert ("an integer is required" in msg or # CPython
1639 "unsupported operand type for int(): 'NoneType'" in msg or # old PyPys
1640 "expected integer, got NoneType object" in msg) # newer PyPys
1641 with pytest.raises(TypeError):
1642 p.a1 = "def"
1643 if sys.version_info < (3,):
1644 BEnum2 = new_enum_type(unicode("foo"), (unicode('abc'),), (5,), BInt)
1645 assert string(cast(BEnum2, 5)) == 'abc'
1646 assert type(string(cast(BEnum2, 5))) is str
1647
1648 def test_enum_overflow():
1649 max_uint = 2 ** (size_of_int()*8) - 1
1650 max_int = max_uint // 2
1651 max_ulong = 2 ** (size_of_long()*8) - 1
1652 max_long = max_ulong // 2
1653 for BPrimitive in [new_primitive_type("int"),
1654 new_primitive_type("unsigned int"),
1655 new_primitive_type("long"),
1656 new_primitive_type("unsigned long")]:
1657 for x in [max_uint, max_int, max_ulong, max_long]:
1658 for testcase in [x, x+1, -x-1, -x-2]:
1659 if int(cast(BPrimitive, testcase)) == testcase:
1660 # fits
1661 BEnum = new_enum_type("foo", ("AA",), (testcase,),
1662 BPrimitive)
1663 assert int(cast(BEnum, testcase)) == testcase
1664 else:
1665 # overflows
1666 pytest.raises(OverflowError, new_enum_type,
1667 "foo", ("AA",), (testcase,), BPrimitive)
1668
1669 def test_callback_returning_enum():
1670 BInt = new_primitive_type("int")
1671 BEnum = new_enum_type("foo", ('def', 'c', 'ab'), (0, 1, -20), BInt)
1672 def cb(n):
1673 if n & 1:
1674 return cast(BEnum, n)
1675 else:
1676 return n
1677 BFunc = new_function_type((BInt,), BEnum)
1678 f = callback(BFunc, cb)
1679 assert f(0) == 0
1680 assert f(1) == 1
1681 assert f(-20) == -20
1682 assert f(20) == 20
1683 assert f(21) == 21
1684
1685 def test_callback_returning_enum_unsigned():
1686 BInt = new_primitive_type("int")
1687 BUInt = new_primitive_type("unsigned int")
1688 BEnum = new_enum_type("foo", ('def', 'c', 'ab'), (0, 1, 20), BUInt)
1689 def cb(n):
1690 if n & 1:
1691 return cast(BEnum, n)
1692 else:
1693 return n
1694 BFunc = new_function_type((BInt,), BEnum)
1695 f = callback(BFunc, cb)
1696 assert f(0) == 0
1697 assert f(1) == 1
1698 assert f(-21) == 2**32 - 21
1699 assert f(20) == 20
1700 assert f(21) == 21
1701
1702 def test_callback_returning_char():
1703 BInt = new_primitive_type("int")
1704 BChar = new_primitive_type("char")
1705 def cb(n):
1706 return bytechr(n)
1707 BFunc = new_function_type((BInt,), BChar)
1708 f = callback(BFunc, cb)
1709 assert f(0) == b'\x00'
1710 assert f(255) == b'\xFF'
1711
1712 def _hacked_pypy_uni4():
1713 pyuni4 = {1: True, 2: False}[len(u+'\U00012345')]
1714 return 'PY_DOT_PY' in globals() and not pyuni4
1715
1716 def test_callback_returning_wchar_t():
1717 BInt = new_primitive_type("int")
1718 BWChar = new_primitive_type("wchar_t")
1719 def cb(n):
1720 if n == -1:
1721 return u+'\U00012345'
1722 if n == -2:
1723 raise ValueError
1724 return unichr(n)
1725 BFunc = new_function_type((BInt,), BWChar)
1726 f = callback(BFunc, cb)
1727 assert f(0) == unichr(0)
1728 assert f(255) == unichr(255)
1729 assert f(0x1234) == u+'\u1234'
1730 if sizeof(BWChar) == 4 and not _hacked_pypy_uni4():
1731 assert f(-1) == u+'\U00012345'
1732 assert f(-2) == u+'\x00' # and an exception printed to stderr
1733
1734 def test_struct_with_bitfields():
1735 BLong = new_primitive_type("long")
1736 BStruct = new_struct_type("struct foo")
1737 LONGBITS = 8 * sizeof(BLong)
1738 complete_struct_or_union(BStruct, [('a1', BLong, 1),
1739 ('a2', BLong, 2),
1740 ('a3', BLong, 3),
1741 ('a4', BLong, LONGBITS - 5)])
1742 d = BStruct.fields
1743 assert d[0][1].offset == d[1][1].offset == d[2][1].offset == 0
1744 assert d[3][1].offset == sizeof(BLong)
1745 def f(m, r):
1746 if sys.byteorder == 'little':
1747 return r
1748 else:
1749 return LONGBITS - m - r
1750 assert d[0][1].bitshift == f(1, 0)
1751 assert d[0][1].bitsize == 1
1752 assert d[1][1].bitshift == f(2, 1)
1753 assert d[1][1].bitsize == 2
1754 assert d[2][1].bitshift == f(3, 3)
1755 assert d[2][1].bitsize == 3
1756 assert d[3][1].bitshift == f(LONGBITS - 5, 0)
1757 assert d[3][1].bitsize == LONGBITS - 5
1758 assert sizeof(BStruct) == 2 * sizeof(BLong)
1759 assert alignof(BStruct) == alignof(BLong)
1760
1761 def test_bitfield_instance():
1762 BInt = new_primitive_type("int")
1763 BUnsignedInt = new_primitive_type("unsigned int")
1764 BStruct = new_struct_type("struct foo")
1765 complete_struct_or_union(BStruct, [('a1', BInt, 1),
1766 ('a2', BUnsignedInt, 2),
1767 ('a3', BInt, 3)])
1768 p = newp(new_pointer_type(BStruct), None)
1769 p.a1 = -1
1770 assert p.a1 == -1
1771 p.a1 = 0
1772 with pytest.raises(OverflowError):
1773 p.a1 = 2
1774 assert p.a1 == 0
1775 #
1776 p.a1 = -1
1777 p.a2 = 3
1778 p.a3 = -4
1779 with pytest.raises(OverflowError):
1780 p.a3 = 4
1781 with pytest.raises(OverflowError) as e:
1782 p.a3 = -5
1783 assert str(e.value) == ("value -5 outside the range allowed by the "
1784 "bit field width: -4 <= x <= 3")
1785 assert p.a1 == -1 and p.a2 == 3 and p.a3 == -4
1786 #
1787 # special case for convenience: "int x:1", while normally signed,
1788 # allows also setting the value "1" (it still gets read back as -1)
1789 p.a1 = 1
1790 assert p.a1 == -1
1791 with pytest.raises(OverflowError) as e:
1792 p.a1 = -2
1793 assert str(e.value) == ("value -2 outside the range allowed by the "
1794 "bit field width: -1 <= x <= 1")
1795
1796 def test_bitfield_instance_init():
1797 BInt = new_primitive_type("int")
1798 BStruct = new_struct_type("struct foo")
1799 complete_struct_or_union(BStruct, [('a1', BInt, 1)])
1800 p = newp(new_pointer_type(BStruct), [-1])
1801 assert p.a1 == -1
1802 p = newp(new_pointer_type(BStruct), {'a1': -1})
1803 assert p.a1 == -1
1804 #
1805 BUnion = new_union_type("union bar")
1806 complete_struct_or_union(BUnion, [('a1', BInt, 1)])
1807 p = newp(new_pointer_type(BUnion), [-1])
1808 assert p.a1 == -1
1809
1810 def test_weakref():
1811 import _weakref
1812 BInt = new_primitive_type("int")
1813 BPtr = new_pointer_type(BInt)
1814 rlist = [_weakref.ref(BInt),
1815 _weakref.ref(newp(BPtr, 42)),
1816 _weakref.ref(cast(BPtr, 42)),
1817 _weakref.ref(cast(BInt, 42)),
1818 _weakref.ref(buffer(newp(BPtr, 42))),
1819 ]
1820 for i in range(5):
1821 import gc; gc.collect()
1822 if [r() for r in rlist] == [None for r in rlist]:
1823 break
1824
1825 def test_no_inheritance():
1826 BInt = new_primitive_type("int")
1827 try:
1828 class foo(type(BInt)): pass
1829 except TypeError:
1830 pass
1831 else:
1832 raise AssertionError
1833 x = cast(BInt, 42)
1834 try:
1835 class foo(type(x)): pass
1836 except TypeError:
1837 pass
1838 else:
1839 raise AssertionError
1840
1841 def test_assign_string():
1842 BChar = new_primitive_type("char")
1843 BArray1 = new_array_type(new_pointer_type(BChar), 5)
1844 BArray2 = new_array_type(new_pointer_type(BArray1), 5)
1845 a = newp(BArray2, [b"abc", b"de", b"ghij"])
1846 assert string(a[1]) == b"de"
1847 assert string(a[2]) == b"ghij"
1848 a[2] = b"."
1849 assert string(a[2]) == b"."
1850 a[2] = b"12345"
1851 assert string(a[2]) == b"12345"
1852 with pytest.raises(IndexError) as e:
1853 a[2] = b"123456"
1854 assert 'char[5]' in str(e.value)
1855 assert 'got 6 characters' in str(e.value)
1856
1857 def test_add_error():
1858 x = cast(new_primitive_type("int"), 42)
1859 with pytest.raises(TypeError):
1860 x + 1
1861 with pytest.raises(TypeError):
1862 x - 1
1863
1864 def test_void_errors():
1865 pytest.raises(ValueError, alignof, new_void_type())
1866 pytest.raises(TypeError, newp, new_pointer_type(new_void_type()), None)
1867
1868 def test_too_many_items():
1869 BChar = new_primitive_type("char")
1870 BArray = new_array_type(new_pointer_type(BChar), 5)
1871 pytest.raises(IndexError, newp, BArray, tuple(b'123456'))
1872 pytest.raises(IndexError, newp, BArray, list(b'123456'))
1873 pytest.raises(IndexError, newp, BArray, b'123456')
1874 BStruct = new_struct_type("struct foo")
1875 complete_struct_or_union(BStruct, [])
1876 pytest.raises(TypeError, newp, new_pointer_type(BStruct), b'')
1877 pytest.raises(ValueError, newp, new_pointer_type(BStruct), [b'1'])
1878
1879 def test_more_type_errors():
1880 BInt = new_primitive_type("int")
1881 BChar = new_primitive_type("char")
1882 BArray = new_array_type(new_pointer_type(BChar), 5)
1883 pytest.raises(TypeError, newp, BArray, 12.34)
1884 BArray = new_array_type(new_pointer_type(BInt), 5)
1885 pytest.raises(TypeError, newp, BArray, 12.34)
1886 BFloat = new_primitive_type("float")
1887 pytest.raises(TypeError, cast, BFloat, newp(BArray, None))
1888
1889 def test_more_overflow_errors():
1890 BUInt = new_primitive_type("unsigned int")
1891 pytest.raises(OverflowError, newp, new_pointer_type(BUInt), -1)
1892 pytest.raises(OverflowError, newp, new_pointer_type(BUInt), 2**32)
1893
1894 def test_newp_copying():
1895 """Test that we can do newp(<type>, <cdata of the given type>) for most
1896 types, including same-type arrays.
1897 """
1898 BInt = new_primitive_type("int")
1899 p = newp(new_pointer_type(BInt), cast(BInt, 42))
1900 assert p[0] == 42
1901 #
1902 BUInt = new_primitive_type("unsigned int")
1903 p = newp(new_pointer_type(BUInt), cast(BUInt, 42))
1904 assert p[0] == 42
1905 #
1906 BChar = new_primitive_type("char")
1907 p = newp(new_pointer_type(BChar), cast(BChar, '!'))
1908 assert p[0] == b'!'
1909 #
1910 BFloat = new_primitive_type("float")
1911 p = newp(new_pointer_type(BFloat), cast(BFloat, 12.25))
1912 assert p[0] == 12.25
1913 #
1914 BStruct = new_struct_type("struct foo_s")
1915 BStructPtr = new_pointer_type(BStruct)
1916 complete_struct_or_union(BStruct, [('a1', BInt, -1)])
1917 s1 = newp(BStructPtr, [42])
1918 p1 = newp(new_pointer_type(BStructPtr), s1)
1919 assert p1[0] == s1
1920 #
1921 BArray = new_array_type(new_pointer_type(BInt), None)
1922 a1 = newp(BArray, [1, 2, 3, 4])
1923 pytest.raises(TypeError, newp, BArray, a1)
1924 BArray6 = new_array_type(new_pointer_type(BInt), 6)
1925 a1 = newp(BArray6, [10, 20, 30])
1926 a2 = newp(BArray6, a1)
1927 assert list(a2) == [10, 20, 30, 0, 0, 0]
1928 #
1929 s1 = newp(BStructPtr, [42])
1930 s2 = newp(BStructPtr, s1[0])
1931 assert s2.a1 == 42
1932 #
1933 BUnion = new_union_type("union foo_u")
1934 BUnionPtr = new_pointer_type(BUnion)
1935 complete_struct_or_union(BUnion, [('a1', BInt, -1)])
1936 u1 = newp(BUnionPtr, [42])
1937 u2 = newp(BUnionPtr, u1[0])
1938 assert u2.a1 == 42
1939 #
1940 BFunc = new_function_type((BInt,), BUInt)
1941 p1 = cast(BFunc, 42)
1942 p2 = newp(new_pointer_type(BFunc), p1)
1943 assert p2[0] == p1
1944
1945 def test_string():
1946 BChar = new_primitive_type("char")
1947 assert string(cast(BChar, 42)) == b'*'
1948 assert string(cast(BChar, 0)) == b'\x00'
1949 BCharP = new_pointer_type(BChar)
1950 BArray = new_array_type(BCharP, 10)
1951 a = newp(BArray, b"hello")
1952 assert len(a) == 10
1953 assert string(a) == b"hello"
1954 p = a + 2
1955 assert string(p) == b"llo"
1956 assert string(newp(new_array_type(BCharP, 4), b"abcd")) == b"abcd"
1957 pytest.raises(RuntimeError, string, cast(BCharP, 0))
1958 assert string(a, 4) == b"hell"
1959 assert string(a, 5) == b"hello"
1960 assert string(a, 6) == b"hello"
1961
1962 def test_string_byte():
1963 BByte = new_primitive_type("signed char")
1964 assert string(cast(BByte, 42)) == b'*'
1965 assert string(cast(BByte, 0)) == b'\x00'
1966 BArray = new_array_type(new_pointer_type(BByte), None)
1967 a = newp(BArray, [65, 66, 67])
1968 assert type(string(a)) is bytes and string(a) == b'ABC'
1969 #
1970 BByte = new_primitive_type("unsigned char")
1971 assert string(cast(BByte, 42)) == b'*'
1972 assert string(cast(BByte, 0)) == b'\x00'
1973 BArray = new_array_type(new_pointer_type(BByte), None)
1974 a = newp(BArray, [65, 66, 67])
1975 assert type(string(a)) is bytes and string(a) == b'ABC'
1976 if 'PY_DOT_PY' not in globals() and sys.version_info < (3,):
1977 assert string(a, 8).startswith(b'ABC') # may contain additional garbage
1978
1979 def test_string_wchar():
1980 for typename in ["wchar_t", "char16_t", "char32_t"]:
1981 _test_string_wchar_variant(typename)
1982
1983 def _test_string_wchar_variant(typename):
1984 BWChar = new_primitive_type(typename)
1985 assert string(cast(BWChar, 42)) == u+'*'
1986 assert string(cast(BWChar, 0x4253)) == u+'\u4253'
1987 assert string(cast(BWChar, 0)) == u+'\x00'
1988 BArray = new_array_type(new_pointer_type(BWChar), None)
1989 a = newp(BArray, [u+'A', u+'B', u+'C'])
1990 assert type(string(a)) is unicode and string(a) == u+'ABC'
1991 if 'PY_DOT_PY' not in globals() and sys.version_info < (3,):
1992 try:
1993 # may contain additional garbage
1994 assert string(a, 8).startswith(u+'ABC')
1995 except ValueError: # garbage contains values > 0x10FFFF
1996 assert sizeof(BWChar) == 4
1997
1998 def test_string_typeerror():
1999 BShort = new_primitive_type("short")
2000 BArray = new_array_type(new_pointer_type(BShort), None)
2001 a = newp(BArray, [65, 66, 67])
2002 pytest.raises(TypeError, string, a)
2003
2004 def test_bug_convert_to_ptr():
2005 BChar = new_primitive_type("char")
2006 BCharP = new_pointer_type(BChar)
2007 BDouble = new_primitive_type("double")
2008 x = cast(BDouble, 42)
2009 pytest.raises(TypeError, newp, new_pointer_type(BCharP), x)
2010
2011 def test_set_struct_fields():
2012 BChar = new_primitive_type("char")
2013 BCharP = new_pointer_type(BChar)
2014 BCharArray10 = new_array_type(BCharP, 10)
2015 BStruct = new_struct_type("struct foo")
2016 BStructPtr = new_pointer_type(BStruct)
2017 complete_struct_or_union(BStruct, [('a1', BCharArray10, -1)])
2018 p = newp(BStructPtr, None)
2019 assert string(p.a1) == b''
2020 p.a1 = b'foo'
2021 assert string(p.a1) == b'foo'
2022 assert list(p.a1) == [b'f', b'o', b'o'] + [b'\x00'] * 7
2023 p.a1 = [b'x', b'y']
2024 assert string(p.a1) == b'xyo'
2025
2026 def test_invalid_function_result_types():
2027 BFunc = new_function_type((), new_void_type())
2028 BArray = new_array_type(new_pointer_type(BFunc), 5) # works
2029 new_function_type((), BFunc) # works
2030 new_function_type((), new_primitive_type("int"))
2031 new_function_type((), new_pointer_type(BFunc))
2032 BUnion = new_union_type("union foo_u")
2033 complete_struct_or_union(BUnion, [])
2034 BFunc = new_function_type((), BUnion)
2035 pytest.raises(NotImplementedError, cast(BFunc, 123))
2036 pytest.raises(TypeError, new_function_type, (), BArray)
2037
2038 def test_struct_return_in_func():
2039 BChar = new_primitive_type("char")
2040 BShort = new_primitive_type("short")
2041 BFloat = new_primitive_type("float")
2042 BDouble = new_primitive_type("double")
2043 BInt = new_primitive_type("int")
2044 BStruct = new_struct_type("struct foo_s")
2045 complete_struct_or_union(BStruct, [('a1', BChar, -1),
2046 ('a2', BShort, -1)])
2047 BFunc10 = new_function_type((BInt,), BStruct)
2048 f = cast(BFunc10, _testfunc(10))
2049 s = f(40)
2050 assert repr(s) == "<cdata 'struct foo_s' owning 4 bytes>"
2051 assert s.a1 == bytechr(40)
2052 assert s.a2 == 40 * 40
2053 #
2054 BStruct11 = new_struct_type("struct test11")
2055 complete_struct_or_union(BStruct11, [('a1', BInt, -1),
2056 ('a2', BInt, -1)])
2057 BFunc11 = new_function_type((BInt,), BStruct11)
2058 f = cast(BFunc11, _testfunc(11))
2059 s = f(40)
2060 assert repr(s) == "<cdata 'struct test11' owning 8 bytes>"
2061 assert s.a1 == 40
2062 assert s.a2 == 40 * 40
2063 #
2064 BStruct12 = new_struct_type("struct test12")
2065 complete_struct_or_union(BStruct12, [('a1', BDouble, -1),
2066 ])
2067 BFunc12 = new_function_type((BInt,), BStruct12)
2068 f = cast(BFunc12, _testfunc(12))
2069 s = f(40)
2070 assert repr(s) == "<cdata 'struct test12' owning 8 bytes>"
2071 assert s.a1 == 40.0
2072 #
2073 BStruct13 = new_struct_type("struct test13")
2074 complete_struct_or_union(BStruct13, [('a1', BInt, -1),
2075 ('a2', BInt, -1),
2076 ('a3', BInt, -1)])
2077 BFunc13 = new_function_type((BInt,), BStruct13)
2078 f = cast(BFunc13, _testfunc(13))
2079 s = f(40)
2080 assert repr(s) == "<cdata 'struct test13' owning 12 bytes>"
2081 assert s.a1 == 40
2082 assert s.a2 == 40 * 40
2083 assert s.a3 == 40 * 40 * 40
2084 #
2085 BStruct14 = new_struct_type("struct test14")
2086 complete_struct_or_union(BStruct14, [('a1', BFloat, -1),
2087 ])
2088 BFunc14 = new_function_type((BInt,), BStruct14)
2089 f = cast(BFunc14, _testfunc(14))
2090 s = f(40)
2091 assert repr(s) == "<cdata 'struct test14' owning 4 bytes>"
2092 assert s.a1 == 40.0
2093 #
2094 BStruct15 = new_struct_type("struct test15")
2095 complete_struct_or_union(BStruct15, [('a1', BFloat, -1),
2096 ('a2', BInt, -1)])
2097 BFunc15 = new_function_type((BInt,), BStruct15)
2098 f = cast(BFunc15, _testfunc(15))
2099 s = f(40)
2100 assert repr(s) == "<cdata 'struct test15' owning 8 bytes>"
2101 assert s.a1 == 40.0
2102 assert s.a2 == 40 * 40
2103 #
2104 BStruct16 = new_struct_type("struct test16")
2105 complete_struct_or_union(BStruct16, [('a1', BFloat, -1),
2106 ('a2', BFloat, -1)])
2107 BFunc16 = new_function_type((BInt,), BStruct16)
2108 f = cast(BFunc16, _testfunc(16))
2109 s = f(40)
2110 assert repr(s) == "<cdata 'struct test16' owning 8 bytes>"
2111 assert s.a1 == 40.0
2112 assert s.a2 == -40.0
2113 #
2114 BStruct17 = new_struct_type("struct test17")
2115 complete_struct_or_union(BStruct17, [('a1', BInt, -1),
2116 ('a2', BFloat, -1)])
2117 BFunc17 = new_function_type((BInt,), BStruct17)
2118 f = cast(BFunc17, _testfunc(17))
2119 s = f(40)
2120 assert repr(s) == "<cdata 'struct test17' owning 8 bytes>"
2121 assert s.a1 == 40
2122 assert s.a2 == 40.0 * 40.0
2123 #
2124 BStruct17Ptr = new_pointer_type(BStruct17)
2125 BFunc18 = new_function_type((BStruct17Ptr,), BInt)
2126 f = cast(BFunc18, _testfunc(18))
2127 x = f([[40, 2.5]])
2128 assert x == 42
2129 x = f([{'a2': 43.1}])
2130 assert x == 43
2131
2132 def test_cast_with_functionptr():
2133 BFunc = new_function_type((), new_void_type())
2134 BFunc2 = new_function_type((), new_primitive_type("short"))
2135 BCharP = new_pointer_type(new_primitive_type("char"))
2136 BIntP = new_pointer_type(new_primitive_type("int"))
2137 BStruct = new_struct_type("struct foo")
2138 BStructPtr = new_pointer_type(BStruct)
2139 complete_struct_or_union(BStruct, [('a1', BFunc, -1)])
2140 newp(BStructPtr, [cast(BFunc, 0)])
2141 newp(BStructPtr, [cast(BCharP, 0)])
2142 pytest.raises(TypeError, newp, BStructPtr, [cast(BIntP, 0)])
2143 pytest.raises(TypeError, newp, BStructPtr, [cast(BFunc2, 0)])
2144
2145 def test_wchar():
2146 _test_wchar_variant("wchar_t")
2147 if sys.platform.startswith("linux"):
2148 BWChar = new_primitive_type("wchar_t")
2149 assert sizeof(BWChar) == 4
2150 # wchar_t is often signed on Linux, but not always (e.g. on ARM)
2151 assert int(cast(BWChar, -1)) in (-1, 4294967295)
2152
2153 def test_char16():
2154 BChar16 = new_primitive_type("char16_t")
2155 assert sizeof(BChar16) == 2
2156 _test_wchar_variant("char16_t")
2157 assert int(cast(BChar16, -1)) == 0xffff # always unsigned
2158
2159 def test_char32():
2160 BChar32 = new_primitive_type("char32_t")
2161 assert sizeof(BChar32) == 4
2162 _test_wchar_variant("char32_t")
2163 assert int(cast(BChar32, -1)) == 0xffffffff # always unsigned
2164
2165 def _test_wchar_variant(typename):
2166 BWChar = new_primitive_type(typename)
2167 BInt = new_primitive_type("int")
2168 pyuni4 = {1: True, 2: False}[len(u+'\U00012345')]
2169 wchar4 = {2: False, 4: True}[sizeof(BWChar)]
2170 assert str(cast(BWChar, 0x45)) == "<cdata '%s' %s'E'>" % (
2171 typename, mandatory_u_prefix)
2172 assert str(cast(BWChar, 0x1234)) == "<cdata '%s' %s'\u1234'>" % (
2173 typename, mandatory_u_prefix)
2174 if not _hacked_pypy_uni4():
2175 if wchar4:
2176 x = cast(BWChar, 0x12345)
2177 assert str(x) == "<cdata '%s' %s'\U00012345'>" % (
2178 typename, mandatory_u_prefix)
2179 assert int(x) == 0x12345
2180 else:
2181 x = cast(BWChar, 0x18345)
2182 assert str(x) == "<cdata '%s' %s'\u8345'>" % (
2183 typename, mandatory_u_prefix)
2184 assert int(x) == 0x8345
2185 #
2186 BWCharP = new_pointer_type(BWChar)
2187 BStruct = new_struct_type("struct foo_s")
2188 BStructPtr = new_pointer_type(BStruct)
2189 complete_struct_or_union(BStruct, [('a1', BWChar, -1),
2190 ('a2', BWCharP, -1)])
2191 s = newp(BStructPtr)
2192 s.a1 = u+'\x00'
2193 assert s.a1 == u+'\x00'
2194 with pytest.raises(TypeError):
2195 s.a1 = b'a'
2196 with pytest.raises(TypeError):
2197 s.a1 = bytechr(0xFF)
2198 s.a1 = u+'\u1234'
2199 assert s.a1 == u+'\u1234'
2200 if pyuni4:
2201 if wchar4:
2202 s.a1 = u+'\U00012345'
2203 assert s.a1 == u+'\U00012345'
2204 elif wchar4:
2205 if not _hacked_pypy_uni4():
2206 s.a1 = cast(BWChar, 0x12345)
2207 assert s.a1 == u+'\ud808\udf45'
2208 s.a1 = u+'\ud807\udf44'
2209 assert s.a1 == u+'\U00011f44'
2210 else:
2211 with pytest.raises(TypeError):
2212 s.a1 = u+'\U00012345'
2213 #
2214 BWCharArray = new_array_type(BWCharP, None)
2215 a = newp(BWCharArray, u+'hello \u1234 world')
2216 assert len(a) == 14 # including the final null
2217 assert string(a) == u+'hello \u1234 world'
2218 a[13] = u+'!'
2219 assert string(a) == u+'hello \u1234 world!'
2220 assert str(a) == repr(a)
2221 assert a[6] == u+'\u1234'
2222 a[6] = u+'-'
2223 assert string(a) == u+'hello - world!'
2224 assert str(a) == repr(a)
2225 #
2226 if wchar4 and not _hacked_pypy_uni4():
2227 u1 = u+'\U00012345\U00012346\U00012347'
2228 a = newp(BWCharArray, u1)
2229 assert len(a) == 4
2230 assert string(a) == u1
2231 assert len(list(a)) == 4
2232 expected = [u+'\U00012345', u+'\U00012346', u+'\U00012347', unichr(0)]
2233 assert list(a) == expected
2234 got = [a[i] for i in range(4)]
2235 assert got == expected
2236 with pytest.raises(IndexError):
2237 a[4]
2238 #
2239 w = cast(BWChar, 'a')
2240 assert repr(w) == "<cdata '%s' %s'a'>" % (typename, mandatory_u_prefix)
2241 assert str(w) == repr(w)
2242 assert string(w) == u+'a'
2243 assert int(w) == ord('a')
2244 w = cast(BWChar, 0x1234)
2245 assert repr(w) == "<cdata '%s' %s'\u1234'>" % (typename, mandatory_u_prefix)
2246 assert str(w) == repr(w)
2247 assert string(w) == u+'\u1234'
2248 assert int(w) == 0x1234
2249 w = cast(BWChar, u+'\u8234')
2250 assert repr(w) == "<cdata '%s' %s'\u8234'>" % (typename, mandatory_u_prefix)
2251 assert str(w) == repr(w)
2252 assert string(w) == u+'\u8234'
2253 assert int(w) == 0x8234
2254 w = cast(BInt, u+'\u1234')
2255 assert repr(w) == "<cdata 'int' 4660>"
2256 if wchar4 and not _hacked_pypy_uni4():
2257 w = cast(BWChar, u+'\U00012345')
2258 assert repr(w) == "<cdata '%s' %s'\U00012345'>" % (
2259 typename, mandatory_u_prefix)
2260 assert str(w) == repr(w)
2261 assert string(w) == u+'\U00012345'
2262 assert int(w) == 0x12345
2263 w = cast(BInt, u+'\U00012345')
2264 assert repr(w) == "<cdata 'int' 74565>"
2265 pytest.raises(TypeError, cast, BInt, u+'')
2266 pytest.raises(TypeError, cast, BInt, u+'XX')
2267 assert int(cast(BInt, u+'a')) == ord('a')
2268 #
2269 a = newp(BWCharArray, u+'hello - world')
2270 p = cast(BWCharP, a)
2271 assert string(p) == u+'hello - world'
2272 p[6] = u+'\u2345'
2273 assert string(p) == u+'hello \u2345 world'
2274 #
2275 s = newp(BStructPtr, [u+'\u1234', p])
2276 assert s.a1 == u+'\u1234'
2277 assert s.a2 == p
2278 assert str(s.a2) == repr(s.a2)
2279 assert string(s.a2) == u+'hello \u2345 world'
2280 #
2281 q = cast(BWCharP, 0)
2282 assert str(q) == repr(q)
2283 pytest.raises(RuntimeError, string, q)
2284 #
2285 def cb(p):
2286 assert repr(p).startswith("<cdata '%s *' 0x" % typename)
2287 return len(string(p))
2288 BFunc = new_function_type((BWCharP,), BInt, False)
2289 f = callback(BFunc, cb, -42)
2290 assert f(u+'a\u1234b') == 3
2291 #
2292 if wchar4 and not pyuni4 and not _hacked_pypy_uni4():
2293 # try out-of-range wchar_t values
2294 x = cast(BWChar, 1114112)
2295 pytest.raises(ValueError, string, x)
2296 x = cast(BWChar, -1)
2297 pytest.raises(ValueError, string, x)
2298
2299 def test_wchar_variants_mix():
2300 BWChar = new_primitive_type("wchar_t")
2301 BChar16 = new_primitive_type("char16_t")
2302 BChar32 = new_primitive_type("char32_t")
2303 assert int(cast(BChar32, cast(BChar16, -2))) == 0xfffe
2304 assert int(cast(BWChar, cast(BChar16, -2))) == 0xfffe
2305 assert int(cast(BChar16, cast(BChar32, 0x0001f345))) == 0xf345
2306 assert int(cast(BChar16, cast(BWChar, 0x0001f345))) == 0xf345
2307 #
2308 BChar16A = new_array_type(new_pointer_type(BChar16), None)
2309 BChar32A = new_array_type(new_pointer_type(BChar32), None)
2310 x = cast(BChar32, 'A')
2311 pytest.raises(TypeError, newp, BChar16A, [x])
2312 x = cast(BChar16, 'A')
2313 pytest.raises(TypeError, newp, BChar32A, [x])
2314 #
2315 a = newp(BChar16A, u+'\U00012345')
2316 assert len(a) == 3
2317 a = newp(BChar32A, u+'\U00012345')
2318 assert len(a) == 2 # even if the Python unicode string above is 2 chars
2319
2320 def test_keepalive_struct():
2321 # exception to the no-keepalive rule: p=newp(BStructPtr) returns a
2322 # pointer owning the memory, and p[0] returns a pointer to the
2323 # struct that *also* owns the memory
2324 BStruct = new_struct_type("struct foo")
2325 BStructPtr = new_pointer_type(BStruct)
2326 complete_struct_or_union(BStruct, [('a1', new_primitive_type("int"), -1),
2327 ('a2', new_primitive_type("int"), -1),
2328 ('a3', new_primitive_type("int"), -1)])
2329 p = newp(BStructPtr)
2330 assert repr(p) == "<cdata 'struct foo *' owning 12 bytes>"
2331 q = p[0]
2332 assert repr(q) == "<cdata 'struct foo' owning 12 bytes>"
2333 q.a1 = 123456
2334 assert p.a1 == 123456
2335 r = cast(BStructPtr, p)
2336 assert repr(r[0]).startswith("<cdata 'struct foo &' 0x")
2337 del p
2338 import gc; gc.collect()
2339 assert q.a1 == 123456
2340 assert repr(q) == "<cdata 'struct foo' owning 12 bytes>"
2341 assert q.a1 == 123456
2342
2343 def test_nokeepalive_struct():
2344 BStruct = new_struct_type("struct foo")
2345 BStructPtr = new_pointer_type(BStruct)
2346 BStructPtrPtr = new_pointer_type(BStructPtr)
2347 complete_struct_or_union(BStruct, [('a1', new_primitive_type("int"), -1)])
2348 p = newp(BStructPtr)
2349 pp = newp(BStructPtrPtr)
2350 pp[0] = p
2351 s = pp[0][0]
2352 assert repr(s).startswith("<cdata 'struct foo &' 0x")
2353
2354 def test_owning_repr():
2355 BInt = new_primitive_type("int")
2356 BArray = new_array_type(new_pointer_type(BInt), None) # int[]
2357 p = newp(BArray, 7)
2358 assert repr(p) == "<cdata 'int[]' owning 28 bytes>"
2359 assert sizeof(p) == 28
2360 #
2361 BArray = new_array_type(new_pointer_type(BInt), 7) # int[7]
2362 p = newp(BArray, None)
2363 assert repr(p) == "<cdata 'int[7]' owning 28 bytes>"
2364 assert sizeof(p) == 28
2365
2366 def test_cannot_dereference_void():
2367 BVoidP = new_pointer_type(new_void_type())
2368 p = cast(BVoidP, 123456)
2369 with pytest.raises(TypeError):
2370 p[0]
2371 p = cast(BVoidP, 0)
2372 with pytest.raises((TypeError, RuntimeError)):
2373 p[0]
2374
2375 def test_iter():
2376 BInt = new_primitive_type("int")
2377 BIntP = new_pointer_type(BInt)
2378 BArray = new_array_type(BIntP, None) # int[]
2379 p = newp(BArray, 7)
2380 assert list(p) == list(iter(p)) == [0] * 7
2381 #
2382 pytest.raises(TypeError, iter, cast(BInt, 5))
2383 pytest.raises(TypeError, iter, cast(BIntP, 123456))
2384
2385 def test_cmp():
2386 BInt = new_primitive_type("int")
2387 BIntP = new_pointer_type(BInt)
2388 BVoidP = new_pointer_type(new_void_type())
2389 p = newp(BIntP, 123)
2390 q = cast(BInt, 124)
2391 assert (p == q) is False
2392 assert (p != q) is True
2393 assert (q == p) is False
2394 assert (q != p) is True
2395 if strict_compare:
2396 with pytest.raises(TypeError): p < q
2397 with pytest.raises(TypeError): p <= q
2398 with pytest.raises(TypeError): q < p
2399 with pytest.raises(TypeError): q <= p
2400 with pytest.raises(TypeError): p > q
2401 with pytest.raises(TypeError): p >= q
2402 r = cast(BVoidP, p)
2403 assert (p < r) is False
2404 assert (p <= r) is True
2405 assert (p == r) is True
2406 assert (p != r) is False
2407 assert (p > r) is False
2408 assert (p >= r) is True
2409 s = newp(BIntP, 125)
2410 assert (p == s) is False
2411 assert (p != s) is True
2412 assert (p < s) is (p <= s) is (s > p) is (s >= p)
2413 assert (p > s) is (p >= s) is (s < p) is (s <= p)
2414 assert (p < s) ^ (p > s)
2415
2416 def test_buffer():
2417 try:
2418 import __builtin__
2419 except ImportError:
2420 import builtins as __builtin__
2421 BShort = new_primitive_type("short")
2422 s = newp(new_pointer_type(BShort), 100)
2423 assert sizeof(s) == size_of_ptr()
2424 assert sizeof(BShort) == 2
2425 assert len(buffer(s)) == 2
2426 #
2427 BChar = new_primitive_type("char")
2428 BCharArray = new_array_type(new_pointer_type(BChar), None)
2429 c = newp(BCharArray, b"hi there")
2430 #
2431 buf = buffer(c)
2432 assert repr(buf).startswith('<_cffi_backend.buffer object at 0x')
2433 assert bytes(buf) == b"hi there\x00"
2434 assert type(buf) is buffer
2435 if sys.version_info < (3,):
2436 assert str(buf) == "hi there\x00"
2437 assert unicode(buf) == u+"hi there\x00"
2438 else:
2439 assert str(buf) == repr(buf)
2440 # --mb_length--
2441 assert len(buf) == len(b"hi there\x00")
2442 # --mb_item--
2443 for i in range(-12, 12):
2444 try:
2445 expected = b"hi there\x00"[i]
2446 except IndexError:
2447 with pytest.raises(IndexError):
2448 buf[i]
2449 else:
2450 assert buf[i] == bitem2bchr(expected)
2451 # --mb_slice--
2452 assert buf[:] == b"hi there\x00"
2453 for i in range(-12, 12):
2454 assert buf[i:] == b"hi there\x00"[i:]
2455 assert buf[:i] == b"hi there\x00"[:i]
2456 for j in range(-12, 12):
2457 assert buf[i:j] == b"hi there\x00"[i:j]
2458 # --misc--
2459 assert list(buf) == list(map(bitem2bchr, b"hi there\x00"))
2460 # --mb_as_buffer--
2461 if hasattr(__builtin__, 'buffer'): # Python <= 2.7
2462 pytest.raises(TypeError, __builtin__.buffer, c)
2463 bf1 = __builtin__.buffer(buf)
2464 assert len(bf1) == len(buf) and bf1[3] == "t"
2465 if hasattr(__builtin__, 'memoryview'): # Python >= 2.7
2466 pytest.raises(TypeError, memoryview, c)
2467 mv1 = memoryview(buf)
2468 assert len(mv1) == len(buf) and mv1[3] in (b"t", ord(b"t"))
2469 # --mb_ass_item--
2470 expected = list(map(bitem2bchr, b"hi there\x00"))
2471 for i in range(-12, 12):
2472 try:
2473 expected[i] = bytechr(i & 0xff)
2474 except IndexError:
2475 with pytest.raises(IndexError):
2476 buf[i] = bytechr(i & 0xff)
2477 else:
2478 buf[i] = bytechr(i & 0xff)
2479 assert list(buf) == expected
2480 # --mb_ass_slice--
2481 buf[:] = b"hi there\x00"
2482 assert list(buf) == list(c) == list(map(bitem2bchr, b"hi there\x00"))
2483 with pytest.raises(ValueError):
2484 buf[:] = b"shorter"
2485 with pytest.raises(ValueError):
2486 buf[:] = b"this is much too long!"
2487 buf[4:2] = b"" # no effect, but should work
2488 assert buf[:] == b"hi there\x00"
2489 buf[:2] = b"HI"
2490 assert buf[:] == b"HI there\x00"
2491 buf[:2] = b"hi"
2492 expected = list(map(bitem2bchr, b"hi there\x00"))
2493 x = 0
2494 for i in range(-12, 12):
2495 for j in range(-12, 12):
2496 start = i if i >= 0 else i + len(buf)
2497 stop = j if j >= 0 else j + len(buf)
2498 start = max(0, min(len(buf), start))
2499 stop = max(0, min(len(buf), stop))
2500 sample = bytechr(x & 0xff) * (stop - start)
2501 x += 1
2502 buf[i:j] = sample
2503 expected[i:j] = map(bitem2bchr, sample)
2504 assert list(buf) == expected
2505
2506 def test_getcname():
2507 BUChar = new_primitive_type("unsigned char")
2508 BArray = new_array_type(new_pointer_type(BUChar), 123)
2509 assert getcname(BArray, "<-->") == "unsigned char<-->[123]"
2510
2511 def test_errno():
2512 BVoid = new_void_type()
2513 BFunc5 = new_function_type((), BVoid)
2514 f = cast(BFunc5, _testfunc(5))
2515 set_errno(50)
2516 f()
2517 assert get_errno() == 65
2518 f(); f()
2519 assert get_errno() == 95
2520
2521 def test_errno_callback():
2522 if globals().get('PY_DOT_PY'):
2523 pytest.skip("cannot run this test on py.py (e.g. fails on Windows)")
2524 set_errno(95)
2525 def cb():
2526 e = get_errno()
2527 set_errno(e - 6)
2528 BVoid = new_void_type()
2529 BFunc5 = new_function_type((), BVoid)
2530 f = callback(BFunc5, cb)
2531 f()
2532 assert get_errno() == 89
2533 f(); f()
2534 assert get_errno() == 77
2535
2536 def test_cast_to_array():
2537 # not valid in C! extension to get a non-owning <cdata 'int[3]'>
2538 BInt = new_primitive_type("int")
2539 BIntP = new_pointer_type(BInt)
2540 BArray = new_array_type(BIntP, 3)
2541 x = cast(BArray, 0)
2542 assert repr(x) == "<cdata 'int[3]' NULL>"
2543
2544 def test_cast_invalid():
2545 BStruct = new_struct_type("struct foo")
2546 complete_struct_or_union(BStruct, [])
2547 p = cast(new_pointer_type(BStruct), 123456)
2548 s = p[0]
2549 pytest.raises(TypeError, cast, BStruct, s)
2550
2551 def test_bug_float_convertion():
2552 BDouble = new_primitive_type("double")
2553 BDoubleP = new_pointer_type(BDouble)
2554 pytest.raises(TypeError, newp, BDoubleP, "foobar")
2555
2556 def test_bug_delitem():
2557 BChar = new_primitive_type("char")
2558 BCharP = new_pointer_type(BChar)
2559 x = newp(BCharP)
2560 with pytest.raises(TypeError):
2561 del x[0]
2562
2563 def test_bug_delattr():
2564 BLong = new_primitive_type("long")
2565 BStruct = new_struct_type("struct foo")
2566 complete_struct_or_union(BStruct, [('a1', BLong, -1)])
2567 x = newp(new_pointer_type(BStruct))
2568 with pytest.raises(AttributeError):
2569 del x.a1
2570
2571 def test_variable_length_struct():
2572 pytest.skip("later")
2573 BLong = new_primitive_type("long")
2574 BArray = new_array_type(new_pointer_type(BLong), None)
2575 BStruct = new_struct_type("struct foo")
2576 BStructP = new_pointer_type(BStruct)
2577 complete_struct_or_union(BStruct, [('a1', BLong, -1),
2578 ('a2', BArray, -1)])
2579 assert sizeof(BStruct) == size_of_long()
2580 assert alignof(BStruct) == alignof(BLong)
2581 #
2582 pytest.raises(TypeError, newp, BStructP, None)
2583 x = newp(BStructP, 5)
2584 assert sizeof(x) == 6 * size_of_long()
2585 x[4] = 123
2586 assert x[4] == 123
2587 with pytest.raises(IndexError):
2588 x[5]
2589 assert len(x.a2) == 5
2590 #
2591 pytest.raises(TypeError, newp, BStructP, [123])
2592 x = newp(BStructP, [123, 5])
2593 assert x.a1 == 123
2594 assert len(x.a2) == 5
2595 assert list(x.a2) == [0] * 5
2596 #
2597 x = newp(BStructP, {'a2': 5})
2598 assert x.a1 == 0
2599 assert len(x.a2) == 5
2600 assert list(x.a2) == [0] * 5
2601 #
2602 x = newp(BStructP, [123, (4, 5)])
2603 assert x.a1 == 123
2604 assert len(x.a2) == 2
2605 assert list(x.a2) == [4, 5]
2606 #
2607 x = newp(BStructP, {'a2': (4, 5)})
2608 assert x.a1 == 0
2609 assert len(x.a2) == 2
2610 assert list(x.a2) == [4, 5]
2611
2612 def test_autocast_int():
2613 BInt = new_primitive_type("int")
2614 BIntPtr = new_pointer_type(BInt)
2615 BLongLong = new_primitive_type("long long")
2616 BULongLong = new_primitive_type("unsigned long long")
2617 BULongLongPtr = new_pointer_type(BULongLong)
2618 x = newp(BIntPtr, cast(BInt, 42))
2619 assert x[0] == 42
2620 x = newp(BIntPtr, cast(BLongLong, 42))
2621 assert x[0] == 42
2622 x = newp(BIntPtr, cast(BULongLong, 42))
2623 assert x[0] == 42
2624 x = newp(BULongLongPtr, cast(BInt, 42))
2625 assert x[0] == 42
2626 pytest.raises(OverflowError, newp, BULongLongPtr, cast(BInt, -42))
2627 x = cast(BInt, cast(BInt, 42))
2628 assert int(x) == 42
2629 x = cast(BInt, cast(BLongLong, 42))
2630 assert int(x) == 42
2631 x = cast(BInt, cast(BULongLong, 42))
2632 assert int(x) == 42
2633 x = cast(BULongLong, cast(BInt, 42))
2634 assert int(x) == 42
2635 x = cast(BULongLong, cast(BInt, -42))
2636 assert int(x) == 2 ** 64 - 42
2637 x = cast(BIntPtr, cast(BInt, 42))
2638 assert int(cast(BInt, x)) == 42
2639
2640 def test_autocast_float():
2641 BFloat = new_primitive_type("float")
2642 BDouble = new_primitive_type("float")
2643 BFloatPtr = new_pointer_type(BFloat)
2644 x = newp(BFloatPtr, cast(BDouble, 12.5))
2645 assert x[0] == 12.5
2646 x = cast(BFloat, cast(BDouble, 12.5))
2647 assert float(x) == 12.5
2648
2649 def test_longdouble():
2650 py_py = 'PY_DOT_PY' in globals()
2651 BInt = new_primitive_type("int")
2652 BLongDouble = new_primitive_type("long double")
2653 BLongDoublePtr = new_pointer_type(BLongDouble)
2654 BLongDoubleArray = new_array_type(BLongDoublePtr, None)
2655 a = newp(BLongDoubleArray, 1)
2656 x = a[0]
2657 if not py_py:
2658 assert repr(x).startswith("<cdata 'long double' 0.0")
2659 assert float(x) == 0.0
2660 assert int(x) == 0
2661 #
2662 b = newp(BLongDoubleArray, [1.23])
2663 x = b[0]
2664 if not py_py:
2665 assert repr(x).startswith("<cdata 'long double' 1.23")
2666 assert float(x) == 1.23
2667 assert int(x) == 1
2668 #
2669 BFunc19 = new_function_type((BLongDouble, BInt), BLongDouble)
2670 f = cast(BFunc19, _testfunc(19))
2671 start = lstart = 1.5
2672 for i in range(107):
2673 start = 4 * start - start * start
2674 lstart = f(lstart, 1)
2675 lother = f(1.5, 107)
2676 if not py_py:
2677 assert float(lstart) == float(lother)
2678 assert repr(lstart) == repr(lother)
2679 if sizeof(BLongDouble) > sizeof(new_primitive_type("double")):
2680 assert float(lstart) != start
2681 assert repr(lstart).startswith("<cdata 'long double' ")
2682 #
2683 c = newp(BLongDoubleArray, [lstart])
2684 x = c[0]
2685 assert float(f(lstart, 107)) == float(f(x, 107))
2686
2687 def test_get_array_of_length_zero():
2688 for length in [0, 5, 10]:
2689 BLong = new_primitive_type("long")
2690 BLongP = new_pointer_type(BLong)
2691 BArray0 = new_array_type(BLongP, length)
2692 BStruct = new_struct_type("struct foo")
2693 BStructPtr = new_pointer_type(BStruct)
2694 complete_struct_or_union(BStruct, [('a1', BArray0, -1)])
2695 p = newp(BStructPtr, None)
2696 if length == 0:
2697 assert repr(p.a1).startswith("<cdata 'long *' 0x")
2698 else:
2699 assert repr(p.a1).startswith("<cdata 'long[%d]' 0x" % length)
2700
2701 def test_nested_anonymous_struct():
2702 BInt = new_primitive_type("int")
2703 BChar = new_primitive_type("char")
2704 BStruct = new_struct_type("struct foo")
2705 BInnerStruct = new_struct_type("struct foo")
2706 complete_struct_or_union(BInnerStruct, [('a1', BInt, -1),
2707 ('a2', BChar, -1)])
2708 complete_struct_or_union(BStruct, [('', BInnerStruct, -1),
2709 ('a3', BChar, -1)])
2710 assert sizeof(BInnerStruct) == sizeof(BInt) * 2 # with alignment
2711 assert sizeof(BStruct) == sizeof(BInt) * 3 # 'a3' is placed after
2712 d = BStruct.fields
2713 assert len(d) == 3
2714 assert d[0][0] == 'a1'
2715 assert d[0][1].type is BInt
2716 assert d[0][1].offset == 0
2717 assert d[0][1].bitshift == -1
2718 assert d[0][1].bitsize == -1
2719 assert d[1][0] == 'a2'
2720 assert d[1][1].type is BChar
2721 assert d[1][1].offset == sizeof(BInt)
2722 assert d[1][1].bitshift == -1
2723 assert d[1][1].bitsize == -1
2724 assert d[2][0] == 'a3'
2725 assert d[2][1].type is BChar
2726 assert d[2][1].offset == sizeof(BInt) * 2
2727 assert d[2][1].bitshift == -1
2728 assert d[2][1].bitsize == -1
2729
2730 def test_nested_anonymous_struct_2():
2731 BInt = new_primitive_type("int")
2732 BStruct = new_struct_type("struct foo")
2733 BInnerUnion = new_union_type("union bar")
2734 complete_struct_or_union(BInnerUnion, [('a1', BInt, -1),
2735 ('a2', BInt, -1)])
2736 complete_struct_or_union(BStruct, [('b1', BInt, -1),
2737 ('', BInnerUnion, -1),
2738 ('b2', BInt, -1)])
2739 assert sizeof(BInnerUnion) == sizeof(BInt)
2740 assert sizeof(BStruct) == sizeof(BInt) * 3
2741 fields = [(name, fld.offset, fld.flags) for (name, fld) in BStruct.fields]
2742 assert fields == [
2743 ('b1', 0 * sizeof(BInt), 0),
2744 ('a1', 1 * sizeof(BInt), 0),
2745 ('a2', 1 * sizeof(BInt), 1),
2746 ('b2', 2 * sizeof(BInt), 0),
2747 ]
2748
2749 def test_sizeof_union():
2750 # a union has the largest alignment of its members, and a total size
2751 # that is the largest of its items *possibly further aligned* if
2752 # another smaller item has a larger alignment...
2753 BChar = new_primitive_type("char")
2754 BShort = new_primitive_type("short")
2755 assert sizeof(BShort) == alignof(BShort) == 2
2756 BStruct = new_struct_type("struct foo")
2757 complete_struct_or_union(BStruct, [('a1', BChar),
2758 ('a2', BChar),
2759 ('a3', BChar)])
2760 assert sizeof(BStruct) == 3 and alignof(BStruct) == 1
2761 BUnion = new_union_type("union u")
2762 complete_struct_or_union(BUnion, [('s', BStruct),
2763 ('i', BShort)])
2764 assert sizeof(BUnion) == 4
2765 assert alignof(BUnion) == 2
2766
2767 def test_unaligned_struct():
2768 BInt = new_primitive_type("int")
2769 BStruct = new_struct_type("struct foo")
2770 complete_struct_or_union(BStruct, [('b', BInt, -1, 1)],
2771 None, 5, 1)
2772
2773 def test_CData_CType():
2774 CData, CType = _get_types()
2775 BChar = new_primitive_type("char")
2776 BCharP = new_pointer_type(BChar)
2777 nullchr = cast(BChar, 0)
2778 chrref = newp(BCharP, None)
2779 assert isinstance(nullchr, CData)
2780 assert isinstance(chrref, CData)
2781 assert not isinstance(BChar, CData)
2782 assert not isinstance(nullchr, CType)
2783 assert not isinstance(chrref, CType)
2784 assert isinstance(BChar, CType)
2785
2786 def test_no_cdata_float():
2787 BInt = new_primitive_type("int")
2788 BIntP = new_pointer_type(BInt)
2789 BUInt = new_primitive_type("unsigned int")
2790 BUIntP = new_pointer_type(BUInt)
2791 BFloat = new_primitive_type("float")
2792 pytest.raises(TypeError, newp, BIntP, cast(BFloat, 0.0))
2793 pytest.raises(TypeError, newp, BUIntP, cast(BFloat, 0.0))
2794
2795 def test_bool():
2796 BBool = new_primitive_type("_Bool")
2797 BBoolP = new_pointer_type(BBool)
2798 assert int(cast(BBool, False)) == 0
2799 assert int(cast(BBool, True)) == 1
2800 assert bool(cast(BBool, False)) is False # since 1.7
2801 assert bool(cast(BBool, True)) is True
2802 assert int(cast(BBool, 3)) == 1
2803 assert int(cast(BBool, long(3))) == 1
2804 assert int(cast(BBool, long(10)**4000)) == 1
2805 assert int(cast(BBool, -0.1)) == 1
2806 assert int(cast(BBool, -0.0)) == 0
2807 assert int(cast(BBool, '\x00')) == 0
2808 assert int(cast(BBool, '\xff')) == 1
2809 assert newp(BBoolP, False)[0] == 0
2810 assert newp(BBoolP, True)[0] == 1
2811 assert newp(BBoolP, 0)[0] == 0
2812 assert newp(BBoolP, 1)[0] == 1
2813 pytest.raises(TypeError, newp, BBoolP, 1.0)
2814 pytest.raises(TypeError, newp, BBoolP, '\x00')
2815 pytest.raises(OverflowError, newp, BBoolP, 2)
2816 pytest.raises(OverflowError, newp, BBoolP, -1)
2817 BCharP = new_pointer_type(new_primitive_type("char"))
2818 p = newp(BCharP, b'\x01')
2819 q = cast(BBoolP, p)
2820 assert q[0] is True
2821 p = newp(BCharP, b'\x00')
2822 q = cast(BBoolP, p)
2823 assert q[0] is False
2824 pytest.raises(TypeError, string, cast(BBool, False))
2825 BDouble = new_primitive_type("double")
2826 assert int(cast(BBool, cast(BDouble, 0.1))) == 1
2827 assert int(cast(BBool, cast(BDouble, 0.0))) == 0
2828 BBoolA = new_array_type(BBoolP, None)
2829 p = newp(BBoolA, b'\x01\x00')
2830 assert p[0] is True
2831 assert p[1] is False
2832
2833 def test_bool_forbidden_cases():
2834 BBool = new_primitive_type("_Bool")
2835 BBoolP = new_pointer_type(BBool)
2836 BBoolA = new_array_type(BBoolP, None)
2837 BCharP = new_pointer_type(new_primitive_type("char"))
2838 p = newp(BCharP, b'X')
2839 q = cast(BBoolP, p)
2840 with pytest.raises(ValueError):
2841 q[0]
2842 pytest.raises(TypeError, newp, BBoolP, b'\x00')
2843 assert newp(BBoolP, 0)[0] is False
2844 assert newp(BBoolP, 1)[0] is True
2845 pytest.raises(OverflowError, newp, BBoolP, 2)
2846 pytest.raises(OverflowError, newp, BBoolP, -1)
2847 pytest.raises(ValueError, newp, BBoolA, b'\x00\x01\x02')
2848 pytest.raises(OverflowError, newp, BBoolA, [0, 1, 2])
2849 pytest.raises(TypeError, string, newp(BBoolP, 1))
2850 pytest.raises(TypeError, string, newp(BBoolA, [1]))
2851
2852 def test_typeoffsetof():
2853 BChar = new_primitive_type("char")
2854 BStruct = new_struct_type("struct foo")
2855 BStructPtr = new_pointer_type(BStruct)
2856 complete_struct_or_union(BStruct, [('a1', BChar, -1),
2857 ('a2', BChar, -1),
2858 ('a3', BChar, -1)])
2859 pytest.raises(TypeError, typeoffsetof, BStructPtr, None)
2860 pytest.raises(TypeError, typeoffsetof, BStruct, None)
2861 assert typeoffsetof(BStructPtr, 'a1') == (BChar, 0)
2862 assert typeoffsetof(BStruct, 'a1') == (BChar, 0)
2863 assert typeoffsetof(BStructPtr, 'a2') == (BChar, 1)
2864 assert typeoffsetof(BStruct, 'a3') == (BChar, 2)
2865 assert typeoffsetof(BStructPtr, 'a2', 0) == (BChar, 1)
2866 assert typeoffsetof(BStruct, u+'a3') == (BChar, 2)
2867 pytest.raises(TypeError, typeoffsetof, BStructPtr, 'a2', 1)
2868 pytest.raises(KeyError, typeoffsetof, BStructPtr, 'a4')
2869 pytest.raises(KeyError, typeoffsetof, BStruct, 'a5')
2870 pytest.raises(TypeError, typeoffsetof, BStruct, 42)
2871 pytest.raises(TypeError, typeoffsetof, BChar, 'a1')
2872
2873 def test_typeoffsetof_array():
2874 BInt = new_primitive_type("int")
2875 BIntP = new_pointer_type(BInt)
2876 BArray = new_array_type(BIntP, None)
2877 pytest.raises(TypeError, typeoffsetof, BArray, None)
2878 pytest.raises(TypeError, typeoffsetof, BArray, 'a1')
2879 assert typeoffsetof(BArray, 51) == (BInt, 51 * size_of_int())
2880 assert typeoffsetof(BIntP, 51) == (BInt, 51 * size_of_int())
2881 assert typeoffsetof(BArray, -51) == (BInt, -51 * size_of_int())
2882 MAX = sys.maxsize // size_of_int()
2883 assert typeoffsetof(BArray, MAX) == (BInt, MAX * size_of_int())
2884 assert typeoffsetof(BIntP, MAX) == (BInt, MAX * size_of_int())
2885 pytest.raises(OverflowError, typeoffsetof, BArray, MAX + 1)
2886
2887 def test_typeoffsetof_no_bitfield():
2888 BInt = new_primitive_type("int")
2889 BStruct = new_struct_type("struct foo")
2890 complete_struct_or_union(BStruct, [('a1', BInt, 4)])
2891 pytest.raises(TypeError, typeoffsetof, BStruct, 'a1')
2892
2893 def test_rawaddressof():
2894 BChar = new_primitive_type("char")
2895 BCharP = new_pointer_type(BChar)
2896 BStruct = new_struct_type("struct foo")
2897 BStructPtr = new_pointer_type(BStruct)
2898 complete_struct_or_union(BStruct, [('a1', BChar, -1),
2899 ('a2', BChar, -1),
2900 ('a3', BChar, -1)])
2901 p = newp(BStructPtr)
2902 assert repr(p) == "<cdata 'struct foo *' owning 3 bytes>"
2903 s = p[0]
2904 assert repr(s) == "<cdata 'struct foo' owning 3 bytes>"
2905 a = rawaddressof(BStructPtr, s, 0)
2906 assert repr(a).startswith("<cdata 'struct foo *' 0x")
2907 pytest.raises(TypeError, rawaddressof, BStruct, s, 0)
2908 b = rawaddressof(BCharP, s, 0)
2909 assert b == cast(BCharP, p)
2910 c = rawaddressof(BStructPtr, a, 0)
2911 assert c == a
2912 pytest.raises(TypeError, rawaddressof, BStructPtr, cast(BChar, '?'), 0)
2913 #
2914 d = rawaddressof(BCharP, s, 1)
2915 assert d == cast(BCharP, p) + 1
2916 #
2917 e = cast(BCharP, 109238)
2918 f = rawaddressof(BCharP, e, 42)
2919 assert f == e + 42
2920 #
2921 BCharA = new_array_type(BCharP, None)
2922 e = newp(BCharA, 50)
2923 f = rawaddressof(BCharP, e, 42)
2924 assert f == e + 42
2925
2926 def test_newp_signed_unsigned_char():
2927 BCharArray = new_array_type(
2928 new_pointer_type(new_primitive_type("char")), None)
2929 p = newp(BCharArray, b"foo")
2930 assert len(p) == 4
2931 assert list(p) == [b"f", b"o", b"o", b"\x00"]
2932 #
2933 BUCharArray = new_array_type(
2934 new_pointer_type(new_primitive_type("unsigned char")), None)
2935 p = newp(BUCharArray, b"fo\xff")
2936 assert len(p) == 4
2937 assert list(p) == [ord("f"), ord("o"), 0xff, 0]
2938 #
2939 BSCharArray = new_array_type(
2940 new_pointer_type(new_primitive_type("signed char")), None)
2941 p = newp(BSCharArray, b"fo\xff")
2942 assert len(p) == 4
2943 assert list(p) == [ord("f"), ord("o"), -1, 0]
2944
2945 def test_newp_from_bytearray_doesnt_work():
2946 BCharArray = new_array_type(
2947 new_pointer_type(new_primitive_type("char")), None)
2948 pytest.raises(TypeError, newp, BCharArray, bytearray(b"foo"))
2949 p = newp(BCharArray, 5)
2950 buffer(p)[:] = bytearray(b"foo.\x00")
2951 assert len(p) == 5
2952 assert list(p) == [b"f", b"o", b"o", b".", b"\x00"]
2953 p[1:3] = bytearray(b"XY")
2954 assert list(p) == [b"f", b"X", b"Y", b".", b"\x00"]
2955
2956 def test_string_assignment_to_byte_array():
2957 BByteArray = new_array_type(
2958 new_pointer_type(new_primitive_type("unsigned char")), None)
2959 p = newp(BByteArray, 5)
2960 p[0:3] = bytearray(b"XYZ")
2961 assert list(p) == [ord("X"), ord("Y"), ord("Z"), 0, 0]
2962
2963 # XXX hack
2964 if sys.version_info >= (3,):
2965 try:
2966 import posix, io
2967 posix.fdopen = io.open
2968 except ImportError:
2969 pass # win32
2970
2971 def test_FILE():
2972 if sys.platform == "win32":
2973 pytest.skip("testing FILE not implemented")
2974 # XXX patch start
2975 if sys.platform == "darwin":
2976 pytest.skip("testing variadic broken on macos (issue 4937)")
2977 # XXX patch end
2978 BFILE = new_struct_type("struct _IO_FILE")
2979 BFILEP = new_pointer_type(BFILE)
2980 BChar = new_primitive_type("char")
2981 BCharP = new_pointer_type(BChar)
2982 BInt = new_primitive_type("int")
2983 BFunc = new_function_type((BCharP, BFILEP), BInt, False)
2984 BFunc2 = new_function_type((BFILEP, BCharP), BInt, True)
2985 ll = find_and_load_library('c')
2986 fputs = ll.load_function(BFunc, "fputs")
2987 fscanf = ll.load_function(BFunc2, "fscanf")
2988 #
2989 import posix
2990 fdr, fdw = posix.pipe()
2991 fr1 = posix.fdopen(fdr, 'rb', 256)
2992 fw1 = posix.fdopen(fdw, 'wb', 256)
2993 #
2994 fw1.write(b"X")
2995 res = fputs(b"hello world\n", fw1)
2996 assert res >= 0
2997 fw1.flush() # should not be needed
2998 #
2999 p = newp(new_array_type(BCharP, 100), None)
3000 res = fscanf(fr1, b"%s\n", p)
3001 assert res == 1
3002 assert string(p) == b"Xhello"
3003 fr1.close()
3004 fw1.close()
3005
3006 def test_FILE_only_for_FILE_arg():
3007 if sys.platform == "win32":
3008 pytest.skip("testing FILE not implemented")
3009 #
3010 B_NOT_FILE = new_struct_type("struct NOT_FILE")
3011 B_NOT_FILEP = new_pointer_type(B_NOT_FILE)
3012 BChar = new_primitive_type("char")
3013 BCharP = new_pointer_type(BChar)
3014 BInt = new_primitive_type("int")
3015 BFunc = new_function_type((BCharP, B_NOT_FILEP), BInt, False)
3016 ll = find_and_load_library('c')
3017 fputs = ll.load_function(BFunc, "fputs")
3018 #
3019 import posix
3020 fdr, fdw = posix.pipe()
3021 fr1 = posix.fdopen(fdr, 'r')
3022 fw1 = posix.fdopen(fdw, 'w')
3023 #
3024 e = pytest.raises(TypeError, fputs, b"hello world\n", fw1)
3025 assert str(e.value).startswith(
3026 "initializer for ctype 'struct NOT_FILE *' must "
3027 "be a cdata pointer, not ")
3028
3029 def test_FILE_object():
3030 if sys.platform == "win32":
3031 pytest.skip("testing FILE not implemented")
3032 #
3033 BFILE = new_struct_type("FILE")
3034 BFILEP = new_pointer_type(BFILE)
3035 BChar = new_primitive_type("char")
3036 BCharP = new_pointer_type(BChar)
3037 BInt = new_primitive_type("int")
3038 BFunc = new_function_type((BCharP, BFILEP), BInt, False)
3039 BFunc2 = new_function_type((BFILEP,), BInt, False)
3040 ll = find_and_load_library('c')
3041 fputs = ll.load_function(BFunc, "fputs")
3042 fileno = ll.load_function(BFunc2, "fileno")
3043 #
3044 import posix
3045 fdr, fdw = posix.pipe()
3046 fw1 = posix.fdopen(fdw, 'wb', 256)
3047 #
3048 fw1p = cast(BFILEP, fw1)
3049 fw1.write(b"X")
3050 fw1.flush()
3051 res = fputs(b"hello\n", fw1p)
3052 assert res >= 0
3053 res = fileno(fw1p)
3054 assert (res == fdw) == (sys.version_info < (3,))
3055 fw1.close()
3056 #
3057 data = posix.read(fdr, 256)
3058 assert data == b"Xhello\n"
3059 posix.close(fdr)
3060
3061 def test_errno_saved():
3062 set_errno(42)
3063 # a random function that will reset errno to 0 (at least on non-windows)
3064 import os; os.stat('.')
3065 #
3066 res = get_errno()
3067 assert res == 42
3068
3069 def test_GetLastError():
3070 if sys.platform != "win32":
3071 pytest.skip("GetLastError(): only for Windows")
3072 #
3073 lib = find_and_load_library('KERNEL32.DLL')
3074 BInt = new_primitive_type("int")
3075 BVoid = new_void_type()
3076 BFunc1 = new_function_type((BInt,), BVoid, False)
3077 BFunc2 = new_function_type((), BInt, False)
3078 SetLastError = lib.load_function(BFunc1, "SetLastError")
3079 GetLastError = lib.load_function(BFunc2, "GetLastError")
3080 #
3081 SetLastError(42)
3082 # a random function that will reset the real GetLastError() to 0
3083 import nt; nt.stat('.')
3084 #
3085 res = GetLastError()
3086 assert res == 42
3087 #
3088 SetLastError(2)
3089 code, message = getwinerror()
3090 assert code == 2
3091 assert message == "The system cannot find the file specified"
3092 #
3093 code, message = getwinerror(1155)
3094 assert code == 1155
3095 assert message == ("No application is associated with the "
3096 "specified file for this operation")
3097
3098 def test_nonstandard_integer_types():
3099 for typename in ['int8_t', 'uint8_t', 'int16_t', 'uint16_t', 'int32_t',
3100 'uint32_t', 'int64_t', 'uint64_t', 'intptr_t',
3101 'uintptr_t', 'ptrdiff_t', 'size_t', 'ssize_t',
3102 'int_least8_t', 'uint_least8_t',
3103 'int_least16_t', 'uint_least16_t',
3104 'int_least32_t', 'uint_least32_t',
3105 'int_least64_t', 'uint_least64_t',
3106 'int_fast8_t', 'uint_fast8_t',
3107 'int_fast16_t', 'uint_fast16_t',
3108 'int_fast32_t', 'uint_fast32_t',
3109 'int_fast64_t', 'uint_fast64_t',
3110 'intmax_t', 'uintmax_t']:
3111 new_primitive_type(typename) # works
3112
3113 def test_cannot_convert_unicode_to_charp():
3114 BCharP = new_pointer_type(new_primitive_type("char"))
3115 BCharArray = new_array_type(BCharP, None)
3116 pytest.raises(TypeError, newp, BCharArray, u+'foobar')
3117
3118 def test_buffer_keepalive():
3119 BCharP = new_pointer_type(new_primitive_type("char"))
3120 BCharArray = new_array_type(BCharP, None)
3121 buflist = []
3122 for i in range(20):
3123 c = newp(BCharArray, str2bytes("hi there %d" % i))
3124 buflist.append(buffer(c))
3125 import gc; gc.collect()
3126 for i in range(20):
3127 buf = buflist[i]
3128 assert buf[:] == str2bytes("hi there %d\x00" % i)
3129
3130 def test_slice():
3131 BIntP = new_pointer_type(new_primitive_type("int"))
3132 BIntArray = new_array_type(BIntP, None)
3133 c = newp(BIntArray, 5)
3134 assert len(c) == 5
3135 assert repr(c) == "<cdata 'int[]' owning 20 bytes>"
3136 d = c[1:4]
3137 assert len(d) == 3
3138 assert repr(d) == "<cdata 'int[]' sliced length 3>"
3139 d[0] = 123
3140 d[2] = 456
3141 assert c[1] == 123
3142 assert c[3] == 456
3143 assert d[2] == 456
3144 with pytest.raises(IndexError):
3145 d[3]
3146 with pytest.raises(IndexError):
3147 d[-1]
3148
3149 def test_slice_ptr():
3150 BIntP = new_pointer_type(new_primitive_type("int"))
3151 BIntArray = new_array_type(BIntP, None)
3152 c = newp(BIntArray, 5)
3153 d = (c+1)[0:2]
3154 assert len(d) == 2
3155 assert repr(d) == "<cdata 'int[]' sliced length 2>"
3156 d[1] += 50
3157 assert c[2] == 50
3158
3159 def test_slice_array_checkbounds():
3160 BIntP = new_pointer_type(new_primitive_type("int"))
3161 BIntArray = new_array_type(BIntP, None)
3162 c = newp(BIntArray, 5)
3163 c[0:5]
3164 assert len(c[5:5]) == 0
3165 with pytest.raises(IndexError):
3166 c[-1:1]
3167 cp = c + 0
3168 cp[-1:1]
3169
3170 def test_nonstandard_slice():
3171 BIntP = new_pointer_type(new_primitive_type("int"))
3172 BIntArray = new_array_type(BIntP, None)
3173 c = newp(BIntArray, 5)
3174 with pytest.raises(IndexError) as e:
3175 c[:5]
3176 assert str(e.value) == "slice start must be specified"
3177 with pytest.raises(IndexError) as e:
3178 c[4:]
3179 assert str(e.value) == "slice stop must be specified"
3180 with pytest.raises(IndexError) as e:
3181 c[1:2:3]
3182 assert str(e.value) == "slice with step not supported"
3183 with pytest.raises(IndexError) as e:
3184 c[1:2:1]
3185 assert str(e.value) == "slice with step not supported"
3186 with pytest.raises(IndexError) as e:
3187 c[4:2]
3188 assert str(e.value) == "slice start > stop"
3189 with pytest.raises(IndexError) as e:
3190 c[6:6]
3191 assert str(e.value) == "index too large (expected 6 <= 5)"
3192
3193 def test_setslice():
3194 BIntP = new_pointer_type(new_primitive_type("int"))
3195 BIntArray = new_array_type(BIntP, None)
3196 c = newp(BIntArray, 5)
3197 c[1:3] = [100, 200]
3198 assert list(c) == [0, 100, 200, 0, 0]
3199 cp = c + 3
3200 cp[-1:1] = [300, 400]
3201 assert list(c) == [0, 100, 300, 400, 0]
3202 cp[-1:1] = iter([500, 600])
3203 assert list(c) == [0, 100, 500, 600, 0]
3204 with pytest.raises(ValueError):
3205 cp[-1:1] = [1000]
3206 assert list(c) == [0, 100, 1000, 600, 0]
3207 with pytest.raises(ValueError):
3208 cp[-1:1] = (700, 800, 900)
3209 assert list(c) == [0, 100, 700, 800, 0]
3210
3211 def test_setslice_array():
3212 BIntP = new_pointer_type(new_primitive_type("int"))
3213 BIntArray = new_array_type(BIntP, None)
3214 c = newp(BIntArray, 5)
3215 d = newp(BIntArray, [10, 20, 30])
3216 c[1:4] = d
3217 assert list(c) == [0, 10, 20, 30, 0]
3218 #
3219 BShortP = new_pointer_type(new_primitive_type("short"))
3220 BShortArray = new_array_type(BShortP, None)
3221 d = newp(BShortArray, [40, 50])
3222 c[1:3] = d
3223 assert list(c) == [0, 40, 50, 30, 0]
3224
3225 def test_cdata_name_module_doc():
3226 p = new_primitive_type("signed char")
3227 x = cast(p, 17)
3228 assert x.__module__ == '_cffi_backend'
3229 assert x.__name__ == '<cdata>'
3230 assert hasattr(x, '__doc__')
3231
3232 def test_different_types_of_ptr_equality():
3233 BVoidP = new_pointer_type(new_void_type())
3234 BIntP = new_pointer_type(new_primitive_type("int"))
3235 x = cast(BVoidP, 12345)
3236 assert x == cast(BIntP, 12345)
3237 assert x != cast(BIntP, 12344)
3238 assert hash(x) == hash(cast(BIntP, 12345))
3239
3240 def test_new_handle():
3241 import _weakref
3242 BVoidP = new_pointer_type(new_void_type())
3243 BCharP = new_pointer_type(new_primitive_type("char"))
3244 class mylist(list):
3245 pass
3246 o = mylist([2, 3, 4])
3247 x = newp_handle(BVoidP, o)
3248 assert repr(x) == "<cdata 'void *' handle to [2, 3, 4]>"
3249 assert x
3250 assert from_handle(x) is o
3251 assert from_handle(cast(BCharP, x)) is o
3252 wr = _weakref.ref(o)
3253 del o
3254 import gc; gc.collect()
3255 assert wr() is not None
3256 assert from_handle(x) == list((2, 3, 4))
3257 assert from_handle(cast(BCharP, x)) == list((2, 3, 4))
3258 del x
3259 for i in range(3):
3260 if wr() is not None:
3261 import gc; gc.collect()
3262 assert wr() is None
3263 pytest.raises(RuntimeError, from_handle, cast(BCharP, 0))
3264
3265 def test_new_handle_cycle():
3266 import _weakref
3267 BVoidP = new_pointer_type(new_void_type())
3268 class A(object):
3269 pass
3270 o = A()
3271 o.cycle = newp_handle(BVoidP, o)
3272 wr = _weakref.ref(o)
3273 del o
3274 for i in range(3):
3275 if wr() is not None:
3276 import gc; gc.collect()
3277 assert wr() is None
3278
3279 def _test_bitfield_details(flag):
3280 BChar = new_primitive_type("char")
3281 BShort = new_primitive_type("short")
3282 BInt = new_primitive_type("int")
3283 BUInt = new_primitive_type("unsigned int")
3284 BStruct = new_struct_type("struct foo1")
3285 complete_struct_or_union(BStruct, [('a', BChar, -1),
3286 ('b1', BInt, 9),
3287 ('b2', BUInt, 7),
3288 ('c', BChar, -1)], -1, -1, -1, flag)
3289 if not (flag & SF_MSVC_BITFIELDS): # gcc, any variant
3290 assert typeoffsetof(BStruct, 'c') == (BChar, 3)
3291 assert sizeof(BStruct) == 4
3292 else: # msvc
3293 assert typeoffsetof(BStruct, 'c') == (BChar, 8)
3294 assert sizeof(BStruct) == 12
3295 assert alignof(BStruct) == 4
3296 #
3297 p = newp(new_pointer_type(BStruct), None)
3298 p.a = b'A'
3299 p.b1 = -201
3300 p.b2 = 99
3301 p.c = b'\x9D'
3302 raw = buffer(p)[:]
3303 if sys.byteorder == 'little':
3304 if flag & SF_MSVC_BITFIELDS:
3305 assert raw == b'A\x00\x00\x007\xC7\x00\x00\x9D\x00\x00\x00'
3306 elif flag & SF_GCC_LITTLE_ENDIAN:
3307 assert raw == b'A7\xC7\x9D'
3308 elif flag & SF_GCC_BIG_ENDIAN:
3309 assert raw == b'A\xE3\x9B\x9D'
3310 else:
3311 raise AssertionError("bad flag")
3312 else:
3313 if flag & SF_MSVC_BITFIELDS:
3314 assert raw == b'A\x00\x00\x00\x00\x00\xC77\x9D\x00\x00\x00'
3315 elif flag & SF_GCC_LITTLE_ENDIAN:
3316 assert raw == b'A\xC77\x9D'
3317 elif flag & SF_GCC_BIG_ENDIAN:
3318 assert raw == b'A\x9B\xE3\x9D'
3319 else:
3320 raise AssertionError("bad flag")
3321 #
3322 BStruct = new_struct_type("struct foo2")
3323 complete_struct_or_union(BStruct, [('a', BChar, -1),
3324 ('', BShort, 9),
3325 ('c', BChar, -1)], -1, -1, -1, flag)
3326 assert typeoffsetof(BStruct, 'c') == (BChar, 4)
3327 if flag & SF_MSVC_BITFIELDS:
3328 assert sizeof(BStruct) == 6
3329 assert alignof(BStruct) == 2
3330 elif flag & SF_GCC_X86_BITFIELDS:
3331 assert sizeof(BStruct) == 5
3332 assert alignof(BStruct) == 1
3333 elif flag & SF_GCC_ARM_BITFIELDS:
3334 assert sizeof(BStruct) == 6
3335 assert alignof(BStruct) == 2
3336 else:
3337 raise AssertionError("bad flag")
3338 #
3339 BStruct = new_struct_type("struct foo2")
3340 complete_struct_or_union(BStruct, [('a', BChar, -1),
3341 ('', BInt, 0),
3342 ('', BInt, 0),
3343 ('c', BChar, -1)], -1, -1, -1, flag)
3344 if flag & SF_MSVC_BITFIELDS:
3345 assert typeoffsetof(BStruct, 'c') == (BChar, 1)
3346 assert sizeof(BStruct) == 2
3347 assert alignof(BStruct) == 1
3348 elif flag & SF_GCC_X86_BITFIELDS:
3349 assert typeoffsetof(BStruct, 'c') == (BChar, 4)
3350 assert sizeof(BStruct) == 5
3351 assert alignof(BStruct) == 1
3352 elif flag & SF_GCC_ARM_BITFIELDS:
3353 assert typeoffsetof(BStruct, 'c') == (BChar, 4)
3354 assert sizeof(BStruct) == 8
3355 assert alignof(BStruct) == 4
3356 else:
3357 raise AssertionError("bad flag")
3358
3359
3360 SF_MSVC_BITFIELDS = 0x01
3361 SF_GCC_ARM_BITFIELDS = 0x02
3362 SF_GCC_X86_BITFIELDS = 0x10
3363
3364 SF_GCC_BIG_ENDIAN = 0x04
3365 SF_GCC_LITTLE_ENDIAN = 0x40
3366
3367 SF_PACKED = 0x08
3368
3369 def test_bitfield_as_x86_gcc():
3370 _test_bitfield_details(flag=SF_GCC_X86_BITFIELDS|SF_GCC_LITTLE_ENDIAN)
3371
3372 def test_bitfield_as_msvc():
3373 _test_bitfield_details(flag=SF_MSVC_BITFIELDS|SF_GCC_LITTLE_ENDIAN)
3374
3375 def test_bitfield_as_arm_gcc():
3376 _test_bitfield_details(flag=SF_GCC_ARM_BITFIELDS|SF_GCC_LITTLE_ENDIAN)
3377
3378 def test_bitfield_as_ppc_gcc():
3379 # PowerPC uses the same format as X86, but is big-endian
3380 _test_bitfield_details(flag=SF_GCC_X86_BITFIELDS|SF_GCC_BIG_ENDIAN)
3381
3382
3383 def buffer_warning(cdata):
3384 import warnings
3385 buf = buffer(cdata)
3386 bytes = len(buf)
3387 with warnings.catch_warnings(record=True) as w:
3388 warnings.simplefilter("always")
3389 buffer(cdata, bytes)
3390 assert len(w) == 0
3391 buffer(cdata, bytes + 1)
3392 assert len(w) <= 1
3393 return len(w) == 1
3394
3395 def test_struct_array_no_length():
3396 BInt = new_primitive_type("int")
3397 BIntP = new_pointer_type(BInt)
3398 BArray = new_array_type(BIntP, None)
3399 BStruct = new_struct_type("foo")
3400 pytest.raises(TypeError, complete_struct_or_union,
3401 BStruct, [('x', BArray),
3402 ('y', BInt)])
3403 #
3404 BStruct = new_struct_type("foo")
3405 complete_struct_or_union(BStruct, [('x', BInt),
3406 ('y', BArray)])
3407 assert sizeof(BStruct) == size_of_int()
3408 d = BStruct.fields
3409 assert len(d) == 2
3410 assert d[0][0] == 'x'
3411 assert d[0][1].type is BInt
3412 assert d[0][1].offset == 0
3413 assert d[0][1].bitshift == -1
3414 assert d[0][1].bitsize == -1
3415 assert d[1][0] == 'y'
3416 assert d[1][1].type is BArray
3417 assert d[1][1].offset == size_of_int()
3418 assert d[1][1].bitshift == -2
3419 assert d[1][1].bitsize == -1
3420 #
3421 p = newp(new_pointer_type(BStruct))
3422 p.x = 42
3423 assert p.x == 42
3424 assert typeof(p.y) is BArray
3425 assert len(p.y) == 0
3426 assert p.y == cast(BIntP, p) + 1
3427 #
3428 p = newp(new_pointer_type(BStruct), [100])
3429 assert p.x == 100
3430 assert len(p.y) == 0
3431 #
3432 # Tests for
3433 # ffi.new("struct_with_var_array *", [field.., [the_array_items..]])
3434 # ffi.new("struct_with_var_array *", [field.., array_size])
3435 plist = []
3436 for i in range(20):
3437 if i % 2 == 0:
3438 p = newp(new_pointer_type(BStruct), [100, [200, i, 400]])
3439 else:
3440 p = newp(new_pointer_type(BStruct), [100, 3])
3441 p.y[1] = i
3442 p.y[0] = 200
3443 assert p.y[2] == 0
3444 p.y[2] = 400
3445 assert len(p.y) == 3
3446 assert len(p[0].y) == 3
3447 assert len(buffer(p)) == sizeof(BInt) * 4
3448 assert sizeof(p[0]) == sizeof(BInt) * 4
3449 plist.append(p)
3450 for i in range(20):
3451 p = plist[i]
3452 assert p.x == 100
3453 assert p.y[0] == 200
3454 assert p.y[1] == i
3455 assert p.y[2] == 400
3456 assert list(p.y) == [200, i, 400]
3457 #
3458 # the following assignment works, as it normally would, for any array field
3459 p.y = [501, 601]
3460 assert list(p.y) == [501, 601, 400]
3461 p[0].y = [500, 600]
3462 assert list(p[0].y) == [500, 600, 400]
3463 assert repr(p) == "<cdata 'foo *' owning %d bytes>" % (
3464 sizeof(BStruct) + 3 * sizeof(BInt),)
3465 assert repr(p[0]) == "<cdata 'foo' owning %d bytes>" % (
3466 sizeof(BStruct) + 3 * sizeof(BInt),)
3467 assert sizeof(p[0]) == sizeof(BStruct) + 3 * sizeof(BInt)
3468 #
3469 # from a non-owning pointer, we can't get the length
3470 q = cast(new_pointer_type(BStruct), p)
3471 assert q.y[0] == 500
3472 assert q[0].y[0] == 500
3473 pytest.raises(TypeError, len, q.y)
3474 pytest.raises(TypeError, len, q[0].y)
3475 assert typeof(q.y) is BIntP
3476 assert typeof(q[0].y) is BIntP
3477 assert sizeof(q[0]) == sizeof(BStruct)
3478 #
3479 # error cases
3480 with pytest.raises(IndexError):
3481 p.y[4]
3482 with pytest.raises(TypeError):
3483 p.y = cast(BIntP, 0)
3484 with pytest.raises(TypeError):
3485 p.y = 15
3486 with pytest.raises(TypeError):
3487 p.y = None
3488 #
3489 # accepting this may be specified by the C99 standard,
3490 # or a GCC strangeness...
3491 BStruct2 = new_struct_type("bar")
3492 complete_struct_or_union(BStruct2, [('f', BStruct),
3493 ('n', BInt)])
3494 p = newp(new_pointer_type(BStruct2), {'n': 42})
3495 assert p.n == 42
3496 #
3497 # more error cases
3498 pytest.raises(TypeError, newp, new_pointer_type(BStruct), [100, None])
3499 BArray4 = new_array_type(BIntP, 4)
3500 BStruct4 = new_struct_type("test4")
3501 complete_struct_or_union(BStruct4, [('a', BArray4)]) # not varsized
3502 pytest.raises(TypeError, newp, new_pointer_type(BStruct4), [None])
3503 pytest.raises(TypeError, newp, new_pointer_type(BStruct4), [4])
3504 p = newp(new_pointer_type(BStruct4), [[10, 20, 30]])
3505 assert p.a[0] == 10
3506 assert p.a[1] == 20
3507 assert p.a[2] == 30
3508 assert p.a[3] == 0
3509 assert buffer_warning(p)
3510 #
3511 # struct of struct of varsized array
3512 BStruct2 = new_struct_type("bar")
3513 complete_struct_or_union(BStruct2, [('head', BInt),
3514 ('tail', BStruct)])
3515 for i in range(2): # try to detect heap overwrites
3516 p = newp(new_pointer_type(BStruct2), [100, [200, list(range(50))]])
3517 assert p.tail.y[49] == 49
3518 assert buffer_warning(p)
3519 assert not buffer_warning(cast(new_pointer_type(BStruct2), p))
3520 assert not buffer_warning(cast(BIntP, p))
3521
3522 def test_more_buffer_warning():
3523 BChar = new_primitive_type("unsigned char")
3524 BCharP = new_pointer_type(BChar)
3525 BArray = new_array_type(BCharP, 10) # char[10]
3526 p = newp(BArray)
3527 assert buffer_warning(p)
3528 assert not buffer_warning(cast(BCharP, p))
3529 p = newp(BCharP)
3530 assert buffer_warning(p)
3531 assert not buffer_warning(cast(BCharP, p))
3532
3533
3534 def test_struct_array_no_length_explicit_position():
3535 BInt = new_primitive_type("int")
3536 BIntP = new_pointer_type(BInt)
3537 BArray = new_array_type(BIntP, None)
3538 BStruct = new_struct_type("foo")
3539 complete_struct_or_union(BStruct, [('x', BArray, -1, 0), # actually 3 items
3540 ('y', BInt, -1, 12)])
3541 p = newp(new_pointer_type(BStruct), [[10, 20], 30])
3542 assert p.x[0] == 10
3543 assert p.x[1] == 20
3544 assert p.x[2] == 0
3545 assert p.y == 30
3546 p = newp(new_pointer_type(BStruct), {'x': [40], 'y': 50})
3547 assert p.x[0] == 40
3548 assert p.x[1] == 0
3549 assert p.x[2] == 0
3550 assert p.y == 50
3551 p = newp(new_pointer_type(BStruct), {'y': 60})
3552 assert p.x[0] == 0
3553 assert p.x[1] == 0
3554 assert p.x[2] == 0
3555 assert p.y == 60
3556 #
3557 # This "should" work too, allocating a larger structure
3558 # (a bit strange in this case, but useful in general)
3559 plist = []
3560 for i in range(20):
3561 p = newp(new_pointer_type(BStruct), [[10, 20, 30, 40, 50, 60, 70]])
3562 plist.append(p)
3563 for i in range(20):
3564 p = plist[i]
3565 assert p.x[0] == 10
3566 assert p.x[1] == 20
3567 assert p.x[2] == 30
3568 assert p.x[3] == 40 == p.y
3569 assert p.x[4] == 50
3570 assert p.x[5] == 60
3571 assert p.x[6] == 70
3572
3573 def test_struct_array_not_aligned():
3574 # struct a { int x; char y; char z[]; };
3575 # ends up of size 8, but 'z' is at offset 5
3576 BChar = new_primitive_type("char")
3577 BInt = new_primitive_type("int")
3578 BCharP = new_pointer_type(BChar)
3579 BArray = new_array_type(BCharP, None)
3580 BStruct = new_struct_type("foo")
3581 complete_struct_or_union(BStruct, [('x', BInt),
3582 ('y', BChar),
3583 ('z', BArray)])
3584 assert sizeof(BStruct) == 2 * size_of_int()
3585 def offsetof(BType, fieldname):
3586 return typeoffsetof(BType, fieldname)[1]
3587 base = offsetof(BStruct, 'z')
3588 assert base == size_of_int() + 1
3589 #
3590 p = newp(new_pointer_type(BStruct), {'z': 3})
3591 assert sizeof(p[0]) == base + 3
3592 q = newp(new_pointer_type(BStruct), {'z': size_of_int()})
3593 assert sizeof(q) == size_of_ptr()
3594 assert sizeof(q[0]) == base + size_of_int()
3595 assert len(p.z) == 3
3596 assert len(p[0].z) == 3
3597 assert len(q.z) == size_of_int()
3598 assert len(q[0].z) == size_of_int()
3599
3600 def test_ass_slice():
3601 BChar = new_primitive_type("char")
3602 BArray = new_array_type(new_pointer_type(BChar), None)
3603 p = newp(BArray, b"foobar")
3604 p[2:5] = [b"*", b"Z", b"T"]
3605 p[1:3] = b"XY"
3606 assert list(p) == [b"f", b"X", b"Y", b"Z", b"T", b"r", b"\x00"]
3607 with pytest.raises(TypeError):
3608 p[1:5] = u+'XYZT'
3609 with pytest.raises(TypeError):
3610 p[1:5] = [1, 2, 3, 4]
3611 #
3612 for typename in ["wchar_t", "char16_t", "char32_t"]:
3613 BUniChar = new_primitive_type(typename)
3614 BArray = new_array_type(new_pointer_type(BUniChar), None)
3615 p = newp(BArray, u+"foobar")
3616 p[2:5] = [u+"*", u+"Z", u+"T"]
3617 p[1:3] = u+"XY"
3618 assert list(p) == [u+"f", u+"X", u+"Y", u+"Z", u+"T", u+"r", u+"\x00"]
3619 with pytest.raises(TypeError):
3620 p[1:5] = b'XYZT'
3621 with pytest.raises(TypeError):
3622 p[1:5] = [1, 2, 3, 4]
3623
3624 def test_void_p_arithmetic():
3625 BVoid = new_void_type()
3626 BInt = new_primitive_type("intptr_t")
3627 p = cast(new_pointer_type(BVoid), 100000)
3628 assert int(cast(BInt, p)) == 100000
3629 assert int(cast(BInt, p + 42)) == 100042
3630 assert int(cast(BInt, p - (-42))) == 100042
3631 assert (p + 42) - p == 42
3632 q = cast(new_pointer_type(new_primitive_type("char")), 100000)
3633 with pytest.raises(TypeError):
3634 p - q
3635 with pytest.raises(TypeError):
3636 q - p
3637 with pytest.raises(TypeError):
3638 p + cast(new_primitive_type('int'), 42)
3639 with pytest.raises(TypeError):
3640 p - cast(new_primitive_type('int'), 42)
3641
3642 def test_sizeof_sliced_array():
3643 BInt = new_primitive_type("int")
3644 BArray = new_array_type(new_pointer_type(BInt), 10)
3645 p = newp(BArray, None)
3646 assert sizeof(p[2:9]) == 7 * sizeof(BInt)
3647
3648 def test_packed():
3649 BLong = new_primitive_type("long")
3650 BChar = new_primitive_type("char")
3651 BShort = new_primitive_type("short")
3652 for extra_args in [(SF_PACKED,), (0, 1)]:
3653 BStruct = new_struct_type("struct foo")
3654 complete_struct_or_union(BStruct, [('a1', BLong, -1),
3655 ('a2', BChar, -1),
3656 ('a3', BShort, -1)],
3657 None, -1, -1, *extra_args)
3658 d = BStruct.fields
3659 assert len(d) == 3
3660 assert d[0][0] == 'a1'
3661 assert d[0][1].type is BLong
3662 assert d[0][1].offset == 0
3663 assert d[0][1].bitshift == -1
3664 assert d[0][1].bitsize == -1
3665 assert d[1][0] == 'a2'
3666 assert d[1][1].type is BChar
3667 assert d[1][1].offset == sizeof(BLong)
3668 assert d[1][1].bitshift == -1
3669 assert d[1][1].bitsize == -1
3670 assert d[2][0] == 'a3'
3671 assert d[2][1].type is BShort
3672 assert d[2][1].offset == sizeof(BLong) + sizeof(BChar)
3673 assert d[2][1].bitshift == -1
3674 assert d[2][1].bitsize == -1
3675 assert sizeof(BStruct) == sizeof(BLong) + sizeof(BChar) + sizeof(BShort)
3676 assert alignof(BStruct) == 1
3677 #
3678 BStruct2 = new_struct_type("struct foo")
3679 complete_struct_or_union(BStruct2, [('b1', BChar, -1),
3680 ('b2', BLong, -1)],
3681 None, -1, -1, 0, 2)
3682 d = BStruct2.fields
3683 assert len(d) == 2
3684 assert d[0][0] == 'b1'
3685 assert d[0][1].type is BChar
3686 assert d[0][1].offset == 0
3687 assert d[0][1].bitshift == -1
3688 assert d[0][1].bitsize == -1
3689 assert d[1][0] == 'b2'
3690 assert d[1][1].type is BLong
3691 assert d[1][1].offset == 2
3692 assert d[1][1].bitshift == -1
3693 assert d[1][1].bitsize == -1
3694 assert sizeof(BStruct2) == 2 + sizeof(BLong)
3695 assert alignof(BStruct2) == 2
3696
3697 def test_packed_with_bitfields():
3698 if sys.platform == "win32":
3699 pytest.skip("testing gcc behavior")
3700 BLong = new_primitive_type("long")
3701 BChar = new_primitive_type("char")
3702 BStruct = new_struct_type("struct foo")
3703 pytest.raises(NotImplementedError,
3704 complete_struct_or_union,
3705 BStruct, [('a1', BLong, 30),
3706 ('a2', BChar, 5)],
3707 None, -1, -1, SF_PACKED)
3708
3709 def test_from_buffer():
3710 import array
3711 a = array.array('H', [10000, 20000, 30000])
3712 BChar = new_primitive_type("char")
3713 BCharP = new_pointer_type(BChar)
3714 BCharA = new_array_type(BCharP, None)
3715 c = from_buffer(BCharA, a)
3716 assert typeof(c) is BCharA
3717 assert len(c) == 6
3718 assert repr(c) == "<cdata 'char[]' buffer len 6 from 'array.array' object>"
3719 p = new_pointer_type(new_primitive_type("unsigned short"))
3720 cast(p, c)[1] += 500
3721 assert list(a) == [10000, 20500, 30000]
3722
3723 def test_from_buffer_not_str_unicode():
3724 BChar = new_primitive_type("char")
3725 BCharP = new_pointer_type(BChar)
3726 BCharA = new_array_type(BCharP, None)
3727 p1 = from_buffer(BCharA, b"foo")
3728 assert p1 == from_buffer(BCharA, b"foo")
3729 import gc; gc.collect()
3730 assert p1 == from_buffer(BCharA, b"foo")
3731 pytest.raises(TypeError, from_buffer, BCharA, u+"foo")
3732 try:
3733 from __builtin__ import buffer
3734 except ImportError:
3735 pass
3736 else:
3737 # Python 2 only
3738 contents = from_buffer(BCharA, buffer(b"foo"))
3739 assert len(contents) == len(p1)
3740 for i in range(len(contents)):
3741 assert contents[i] == p1[i]
3742 p4 = buffer(u+"foo")
3743 contents = from_buffer(BCharA, buffer(u+"foo"))
3744 assert len(contents) == len(p4)
3745 for i in range(len(contents)):
3746 assert contents[i] == p4[i]
3747 try:
3748 from __builtin__ import memoryview
3749 except ImportError:
3750 pass
3751 else:
3752 contents = from_buffer(BCharA, memoryview(b"foo"))
3753 assert len(contents) == len(p1)
3754 for i in range(len(contents)):
3755 assert contents[i] == p1[i]
3756
3757
3758 def test_from_buffer_bytearray():
3759 a = bytearray(b"xyz")
3760 BChar = new_primitive_type("char")
3761 BCharP = new_pointer_type(BChar)
3762 BCharA = new_array_type(BCharP, None)
3763 p = from_buffer(BCharA, a)
3764 assert typeof(p) is BCharA
3765 assert len(p) == 3
3766 assert repr(p) == "<cdata 'char[]' buffer len 3 from 'bytearray' object>"
3767 assert p[2] == b"z"
3768 p[2] = b"."
3769 assert a[2] == ord(".")
3770 a[2] = ord("?")
3771 assert p[2] == b"?"
3772
3773 def test_from_buffer_more_cases():
3774 try:
3775 from _cffi_backend import _testbuff
3776 except ImportError:
3777 pytest.skip("not for pypy")
3778 BChar = new_primitive_type("char")
3779 BCharP = new_pointer_type(BChar)
3780 BCharA = new_array_type(BCharP, None)
3781 #
3782 def check1(bufobj, expected):
3783 c = from_buffer(BCharA, bufobj)
3784 assert typeof(c) is BCharA
3785 if sys.version_info >= (3,):
3786 expected = [bytes(c, "ascii") for c in expected]
3787 assert list(c) == list(expected)
3788 #
3789 def check(methods, expected, expected_for_memoryview=None):
3790 if sys.version_info >= (3,):
3791 if methods <= 7:
3792 return
3793 if expected_for_memoryview is not None:
3794 expected = expected_for_memoryview
3795 class X(object):
3796 pass
3797 _testbuff(X, methods)
3798 bufobj = X()
3799 check1(bufobj, expected)
3800 try:
3801 from __builtin__ import buffer
3802 bufobjb = buffer(bufobj)
3803 except (TypeError, ImportError):
3804 pass
3805 else:
3806 check1(bufobjb, expected)
3807 try:
3808 bufobjm = memoryview(bufobj)
3809 except (TypeError, NameError):
3810 pass
3811 else:
3812 check1(bufobjm, expected_for_memoryview or expected)
3813 #
3814 check(1, "RDB")
3815 check(2, "WRB")
3816 check(4, "CHB")
3817 check(8, "GTB")
3818 check(16, "ROB")
3819 #
3820 check(1 | 2, "RDB")
3821 check(1 | 4, "RDB")
3822 check(2 | 4, "CHB")
3823 check(1 | 8, "RDB", "GTB")
3824 check(1 | 16, "RDB", "ROB")
3825 check(2 | 8, "WRB", "GTB")
3826 check(2 | 16, "WRB", "ROB")
3827 check(4 | 8, "CHB", "GTB")
3828 check(4 | 16, "CHB", "ROB")
3829
3830 def test_from_buffer_require_writable():
3831 BChar = new_primitive_type("char")
3832 BCharP = new_pointer_type(BChar)
3833 BCharA = new_array_type(BCharP, None)
3834 p1 = from_buffer(BCharA, b"foo", False)
3835 assert p1 == from_buffer(BCharA, b"foo", False)
3836 pytest.raises((TypeError, BufferError), from_buffer, BCharA, b"foo", True)
3837 ba = bytearray(b"foo")
3838 p1 = from_buffer(BCharA, ba, True)
3839 p1[0] = b"g"
3840 assert ba == b"goo"
3841
3842 def test_from_buffer_types():
3843 BInt = new_primitive_type("int")
3844 BIntP = new_pointer_type(BInt)
3845 BIntA = new_array_type(BIntP, None)
3846 lst = [-12345678, 87654321, 489148]
3847 bytestring = bytearray(buffer(newp(BIntA, lst))[:] + b'XYZ')
3848 lst2 = lst + [42, -999999999]
3849 bytestring2 = bytearray(buffer(newp(BIntA, lst2))[:] + b'XYZ')
3850 #
3851 p1 = from_buffer(BIntA, bytestring) # int[]
3852 assert typeof(p1) is BIntA
3853 assert len(p1) == 3
3854 assert p1[0] == lst[0]
3855 assert p1[1] == lst[1]
3856 assert p1[2] == lst[2]
3857 with pytest.raises(IndexError):
3858 p1[3]
3859 with pytest.raises(IndexError):
3860 p1[-1]
3861 #
3862 pytest.raises(TypeError, from_buffer, BInt, bytestring)
3863 #
3864 p2 = from_buffer(BIntP, bytestring) # int *
3865 assert p2 == p1 or 'PY_DOT_PY' in globals()
3866 # note: on py.py ^^^, bytearray buffers are not emulated well enough
3867 assert typeof(p2) is BIntP
3868 assert p2[0] == lst[0]
3869 assert p2[1] == lst[1]
3870 assert p2[2] == lst[2]
3871 # hopefully does not crash, but doesn't raise an exception:
3872 p2[3]
3873 p2[-1]
3874 # not enough data even for one, but this is not enforced:
3875 from_buffer(BIntP, b"")
3876 #
3877 BIntA2 = new_array_type(BIntP, 2)
3878 p2 = from_buffer(BIntA2, bytestring) # int[2]
3879 assert typeof(p2) is BIntA2
3880 assert len(p2) == 2
3881 assert p2[0] == lst[0]
3882 assert p2[1] == lst[1]
3883 with pytest.raises(IndexError):
3884 p2[2]
3885 with pytest.raises(IndexError):
3886 p2[-1]
3887 assert p2 == p1 or 'PY_DOT_PY' in globals()
3888 #
3889 BIntA4 = new_array_type(BIntP, 4) # int[4]: too big
3890 pytest.raises(ValueError, from_buffer, BIntA4, bytestring)
3891 #
3892 BStruct = new_struct_type("foo")
3893 complete_struct_or_union(BStruct, [('a1', BInt, -1),
3894 ('a2', BInt, -1)])
3895 BStructP = new_pointer_type(BStruct)
3896 BStructA = new_array_type(BStructP, None)
3897 p1 = from_buffer(BStructA, bytestring2) # struct[]
3898 assert len(p1) == 2
3899 assert typeof(p1) is BStructA
3900 assert p1[0].a1 == lst2[0]
3901 assert p1[0].a2 == lst2[1]
3902 assert p1[1].a1 == lst2[2]
3903 assert p1[1].a2 == lst2[3]
3904 with pytest.raises(IndexError):
3905 p1[2]
3906 with pytest.raises(IndexError):
3907 p1[-1]
3908 assert repr(p1) == "<cdata 'foo[]' buffer len 2 from 'bytearray' object>"
3909 #
3910 p2 = from_buffer(BStructP, bytestring2) # 'struct *'
3911 assert p2 == p1 or 'PY_DOT_PY' in globals()
3912 assert typeof(p2) is BStructP
3913 assert p2.a1 == lst2[0]
3914 assert p2.a2 == lst2[1]
3915 assert p2[0].a1 == lst2[0]
3916 assert p2[0].a2 == lst2[1]
3917 assert p2[1].a1 == lst2[2]
3918 assert p2[1].a2 == lst2[3]
3919 # does not crash:
3920 p2[2]
3921 p2[-1]
3922 # not enough data even for one, but this is not enforced:
3923 from_buffer(BStructP, b"")
3924 from_buffer(BStructP, b"1234567")
3925 #
3926 release(p1)
3927 assert repr(p1) == "<cdata 'foo[]' buffer RELEASED>"
3928 #
3929 BEmptyStruct = new_struct_type("empty")
3930 complete_struct_or_union(BEmptyStruct, [], Ellipsis, 0)
3931 assert sizeof(BEmptyStruct) == 0
3932 BEmptyStructP = new_pointer_type(BEmptyStruct)
3933 BEmptyStructA = new_array_type(BEmptyStructP, None)
3934 pytest.raises(ZeroDivisionError, from_buffer, # empty[]
3935 BEmptyStructA, bytestring)
3936 #
3937 BEmptyStructA5 = new_array_type(BEmptyStructP, 5)
3938 p1 = from_buffer(BEmptyStructA5, bytestring) # struct empty[5]
3939 assert typeof(p1) is BEmptyStructA5
3940 assert len(p1) == 5
3941 assert (cast(BIntP, p1) == from_buffer(BIntA, bytestring)
3942 or 'PY_DOT_PY' in globals())
3943 #
3944 BVarStruct = new_struct_type("varfoo")
3945 BVarStructP = new_pointer_type(BVarStruct)
3946 complete_struct_or_union(BVarStruct, [('a1', BInt, -1),
3947 ('va', BIntA, -1)])
3948 with pytest.raises(TypeError):
3949 from_buffer(BVarStruct, bytestring)
3950 pv = from_buffer(BVarStructP, bytestring) # varfoo *
3951 assert pv.a1 == lst[0]
3952 assert pv.va[0] == lst[1]
3953 assert pv.va[1] == lst[2]
3954 assert sizeof(pv[0]) == 1 * size_of_int()
3955 with pytest.raises(TypeError):
3956 len(pv.va)
3957 # hopefully does not crash, but doesn't raise an exception:
3958 pv.va[2]
3959 pv.va[-1]
3960 # not enough data even for one, but this is not enforced:
3961 from_buffer(BVarStructP, b"")
3962 assert repr(pv) == "<cdata 'varfoo *' buffer from 'bytearray' object>"
3963 assert repr(pv[0]).startswith("<cdata 'varfoo &' ")
3964 #
3965 release(pv)
3966 assert repr(pv) == "<cdata 'varfoo *' buffer RELEASED>"
3967 assert repr(pv[0]).startswith("<cdata 'varfoo &' ")
3968 #
3969 pv = from_buffer(BVarStructP, bytestring) # make a fresh one
3970 with pytest.raises(ValueError):
3971 release(pv[0])
3972
3973 def test_issue483():
3974 BInt = new_primitive_type("int")
3975 BIntP = new_pointer_type(BInt)
3976 BIntA = new_array_type(BIntP, None)
3977 lst = list(range(25))
3978 bytestring = bytearray(buffer(newp(BIntA, lst))[:] + b'XYZ')
3979 p1 = from_buffer(BIntA, bytestring) # int[]
3980 assert len(buffer(p1)) == 25 * size_of_int()
3981 assert sizeof(p1) == 25 * size_of_int()
3982 #
3983 p2 = from_buffer(BIntP, bytestring)
3984 assert sizeof(p2) == size_of_ptr()
3985 assert len(buffer(p2)) == size_of_int() # first element only, by default
3986
3987 def test_memmove():
3988 Short = new_primitive_type("short")
3989 ShortA = new_array_type(new_pointer_type(Short), None)
3990 Char = new_primitive_type("char")
3991 CharA = new_array_type(new_pointer_type(Char), None)
3992 p = newp(ShortA, [-1234, -2345, -3456, -4567, -5678])
3993 memmove(p, p + 1, 4)
3994 assert list(p) == [-2345, -3456, -3456, -4567, -5678]
3995 p[2] = 999
3996 memmove(p + 2, p, 6)
3997 assert list(p) == [-2345, -3456, -2345, -3456, 999]
3998 memmove(p + 4, newp(CharA, b"\x71\x72"), 2)
3999 if sys.byteorder == 'little':
4000 assert list(p) == [-2345, -3456, -2345, -3456, 0x7271]
4001 else:
4002 assert list(p) == [-2345, -3456, -2345, -3456, 0x7172]
4003
4004 def test_memmove_buffer():
4005 import array
4006 Short = new_primitive_type("short")
4007 ShortA = new_array_type(new_pointer_type(Short), None)
4008 a = array.array('H', [10000, 20000, 30000])
4009 p = newp(ShortA, 5)
4010 memmove(p, a, 6)
4011 assert list(p) == [10000, 20000, 30000, 0, 0]
4012 memmove(p + 1, a, 6)
4013 assert list(p) == [10000, 10000, 20000, 30000, 0]
4014 b = array.array('h', [-1000, -2000, -3000])
4015 memmove(b, a, 4)
4016 assert b.tolist() == [10000, 20000, -3000]
4017 assert a.tolist() == [10000, 20000, 30000]
4018 p[0] = 999
4019 p[1] = 998
4020 p[2] = 997
4021 p[3] = 996
4022 p[4] = 995
4023 memmove(b, p, 2)
4024 assert b.tolist() == [999, 20000, -3000]
4025 memmove(b, p + 2, 4)
4026 assert b.tolist() == [997, 996, -3000]
4027 p[2] = -p[2]
4028 p[3] = -p[3]
4029 memmove(b, p + 2, 6)
4030 assert b.tolist() == [-997, -996, 995]
4031
4032 def test_memmove_readonly_readwrite():
4033 SignedChar = new_primitive_type("signed char")
4034 SignedCharA = new_array_type(new_pointer_type(SignedChar), None)
4035 p = newp(SignedCharA, 5)
4036 memmove(p, b"abcde", 3)
4037 assert list(p) == [ord("a"), ord("b"), ord("c"), 0, 0]
4038 memmove(p, bytearray(b"ABCDE"), 2)
4039 assert list(p) == [ord("A"), ord("B"), ord("c"), 0, 0]
4040 pytest.raises((TypeError, BufferError), memmove, b"abcde", p, 3)
4041 ba = bytearray(b"xxxxx")
4042 memmove(dest=ba, src=p, n=3)
4043 assert ba == bytearray(b"ABcxx")
4044 memmove(ba, b"EFGH", 4)
4045 assert ba == bytearray(b"EFGHx")
4046
4047 def test_memmove_sign_check():
4048 SignedChar = new_primitive_type("signed char")
4049 SignedCharA = new_array_type(new_pointer_type(SignedChar), None)
4050 p = newp(SignedCharA, 5)
4051 pytest.raises(ValueError, memmove, p, p + 1, -1) # not segfault
4052
4053 def test_memmove_bad_cdata():
4054 BInt = new_primitive_type("int")
4055 p = cast(BInt, 42)
4056 pytest.raises(TypeError, memmove, p, bytearray(b'a'), 1)
4057 pytest.raises(TypeError, memmove, bytearray(b'a'), p, 1)
4058
4059 def test_dereference_null_ptr():
4060 BInt = new_primitive_type("int")
4061 BIntPtr = new_pointer_type(BInt)
4062 p = cast(BIntPtr, 0)
4063 with pytest.raises(RuntimeError):
4064 p[0]
4065 with pytest.raises(RuntimeError):
4066 p[0] = 42
4067 with pytest.raises(RuntimeError):
4068 p[42]
4069 with pytest.raises(RuntimeError):
4070 p[42] = -1
4071
4072 def test_mixup():
4073 BStruct1 = new_struct_type("foo")
4074 BStruct2 = new_struct_type("foo") # <= same name as BStruct1
4075 BStruct3 = new_struct_type("bar")
4076 BStruct1Ptr = new_pointer_type(BStruct1)
4077 BStruct2Ptr = new_pointer_type(BStruct2)
4078 BStruct3Ptr = new_pointer_type(BStruct3)
4079 BStruct1PtrPtr = new_pointer_type(BStruct1Ptr)
4080 BStruct2PtrPtr = new_pointer_type(BStruct2Ptr)
4081 BStruct3PtrPtr = new_pointer_type(BStruct3Ptr)
4082 pp1 = newp(BStruct1PtrPtr)
4083 pp2 = newp(BStruct2PtrPtr)
4084 pp3 = newp(BStruct3PtrPtr)
4085 pp1[0] = pp1[0]
4086 with pytest.raises(TypeError) as e:
4087 pp3[0] = pp1[0]
4088 assert str(e.value).startswith("initializer for ctype 'bar *' must be a ")
4089 assert str(e.value).endswith(", not cdata 'foo *'")
4090 with pytest.raises(TypeError) as e:
4091 pp2[0] = pp1[0]
4092 assert str(e.value) == ("initializer for ctype 'foo *' appears indeed to "
4093 "be 'foo *', but the types are different (check "
4094 "that you are not e.g. mixing up different ffi "
4095 "instances)")
4096
4097 def test_stdcall_function_type():
4098 assert FFI_CDECL == FFI_DEFAULT_ABI
4099 try:
4100 stdcall = FFI_STDCALL
4101 except NameError:
4102 stdcall = FFI_DEFAULT_ABI
4103 BInt = new_primitive_type("int")
4104 BFunc = new_function_type((BInt, BInt), BInt, False, stdcall)
4105 if stdcall != FFI_DEFAULT_ABI:
4106 assert repr(BFunc) == "<ctype 'int(__stdcall *)(int, int)'>"
4107 else:
4108 assert repr(BFunc) == "<ctype 'int(*)(int, int)'>"
4109
4110 def test_get_common_types():
4111 d = {}
4112 _get_common_types(d)
4113 assert d['bool'] == '_Bool'
4114
4115 def test_unpack():
4116 BChar = new_primitive_type("char")
4117 BArray = new_array_type(new_pointer_type(BChar), 10) # char[10]
4118 p = newp(BArray, b"abc\x00def")
4119 p0 = p
4120 assert unpack(p, 10) == b"abc\x00def\x00\x00\x00"
4121 assert unpack(p+1, 5) == b"bc\x00de"
4122
4123 for typename in ["wchar_t", "char16_t", "char32_t"]:
4124 BWChar = new_primitive_type(typename)
4125 BArray = new_array_type(new_pointer_type(BWChar), 10) # wchar_t[10]
4126 p = newp(BArray, u"abc\x00def")
4127 assert unpack(p, 10) == u"abc\x00def\x00\x00\x00"
4128
4129 for typename, samples in [
4130 ("uint8_t", [0, 2**8-1]),
4131 ("uint16_t", [0, 2**16-1]),
4132 ("uint32_t", [0, 2**32-1]),
4133 ("uint64_t", [0, 2**64-1]),
4134 ("int8_t", [-2**7, 2**7-1]),
4135 ("int16_t", [-2**15, 2**15-1]),
4136 ("int32_t", [-2**31, 2**31-1]),
4137 ("int64_t", [-2**63, 2**63-1]),
4138 ("_Bool", [False, True]),
4139 ("float", [0.0, 10.5]),
4140 ("double", [12.34, 56.78]),
4141 ]:
4142 BItem = new_primitive_type(typename)
4143 BArray = new_array_type(new_pointer_type(BItem), 10)
4144 p = newp(BArray, samples)
4145 result = unpack(p, len(samples))
4146 assert result == samples
4147 for i in range(len(samples)):
4148 assert result[i] == p[i] and type(result[i]) is type(p[i])
4149 assert (type(result[i]) is bool) == (type(samples[i]) is bool)
4150 #
4151 BInt = new_primitive_type("int")
4152 pytest.raises(TypeError, unpack, p)
4153 pytest.raises(TypeError, unpack, b"foobar", 6)
4154 pytest.raises(TypeError, unpack, cast(BInt, 42), 1)
4155 #
4156 BPtr = new_pointer_type(BInt)
4157 random_ptr = cast(BPtr, -424344)
4158 other_ptr = cast(BPtr, 54321)
4159 BArray = new_array_type(new_pointer_type(BPtr), None)
4160 lst = unpack(newp(BArray, [random_ptr, other_ptr]), 2)
4161 assert lst == [random_ptr, other_ptr]
4162 #
4163 BFunc = new_function_type((BInt, BInt), BInt, False)
4164 BFuncPtr = new_pointer_type(BFunc)
4165 lst = unpack(newp(new_array_type(BFuncPtr, None), 2), 2)
4166 assert len(lst) == 2
4167 assert not lst[0] and not lst[1]
4168 assert typeof(lst[0]) is BFunc
4169 #
4170 BStruct = new_struct_type("foo")
4171 BStructPtr = new_pointer_type(BStruct)
4172 e = pytest.raises(ValueError, unpack, cast(BStructPtr, 42), 5)
4173 assert str(e.value) == "'foo *' points to items of unknown size"
4174 complete_struct_or_union(BStruct, [('a1', BInt, -1),
4175 ('a2', BInt, -1)])
4176 array_of_structs = newp(new_array_type(BStructPtr, None), [[4,5], [6,7]])
4177 lst = unpack(array_of_structs, 2)
4178 assert typeof(lst[0]) is BStruct
4179 assert lst[0].a1 == 4 and lst[1].a2 == 7
4180 #
4181 pytest.raises(RuntimeError, unpack, cast(new_pointer_type(BChar), 0), 0)
4182 pytest.raises(RuntimeError, unpack, cast(new_pointer_type(BChar), 0), 10)
4183 #
4184 pytest.raises(ValueError, unpack, p0, -1)
4185 pytest.raises(ValueError, unpack, p, -1)
4186
4187 def test_cdata_dir():
4188 BInt = new_primitive_type("int")
4189 p = cast(BInt, 42)
4190 check_dir(p, [])
4191 p = newp(new_array_type(new_pointer_type(BInt), None), 5)
4192 check_dir(p, [])
4193 BStruct = new_struct_type("foo")
4194 p = cast(new_pointer_type(BStruct), 0)
4195 check_dir(p, []) # opaque
4196 complete_struct_or_union(BStruct, [('a2', BInt, -1),
4197 ('a1', BInt, -1)])
4198 check_dir(p, ['a1', 'a2']) # always sorted
4199 p = newp(new_pointer_type(BStruct), None)
4200 check_dir(p, ['a1', 'a2'])
4201 check_dir(p[0], ['a1', 'a2'])
4202 pp = newp(new_pointer_type(new_pointer_type(BStruct)), p)
4203 check_dir(pp, [])
4204 check_dir(pp[0], ['a1', 'a2'])
4205 check_dir(pp[0][0], ['a1', 'a2'])
4206
4207 def test_char_pointer_conversion():
4208 import warnings
4209 assert __version__.startswith("1."), (
4210 "the warning will be an error if we ever release cffi 2.x")
4211 BCharP = new_pointer_type(new_primitive_type("char"))
4212 BIntP = new_pointer_type(new_primitive_type("int"))
4213 BVoidP = new_pointer_type(new_void_type())
4214 BUCharP = new_pointer_type(new_primitive_type("unsigned char"))
4215 z1 = cast(BCharP, 0)
4216 z2 = cast(BIntP, 0)
4217 z3 = cast(BVoidP, 0)
4218 z4 = cast(BUCharP, 0)
4219 with warnings.catch_warnings(record=True) as w:
4220 warnings.simplefilter("always")
4221 newp(new_pointer_type(BIntP), z1) # warn
4222 assert len(w) == 1
4223 newp(new_pointer_type(BVoidP), z1) # fine
4224 assert len(w) == 1
4225 newp(new_pointer_type(BCharP), z2) # warn
4226 assert len(w) == 2
4227 newp(new_pointer_type(BVoidP), z2) # fine
4228 assert len(w) == 2
4229 newp(new_pointer_type(BCharP), z3) # fine
4230 assert len(w) == 2
4231 newp(new_pointer_type(BIntP), z3) # fine
4232 assert len(w) == 2
4233 newp(new_pointer_type(BCharP), z4) # fine (ignore signedness here)
4234 assert len(w) == 2
4235 newp(new_pointer_type(BUCharP), z1) # fine (ignore signedness here)
4236 assert len(w) == 2
4237 newp(new_pointer_type(BUCharP), z3) # fine
4238 assert len(w) == 2
4239 # check that the warnings are associated with lines in this file
4240 assert w[1].lineno == w[0].lineno + 4
4241
4242 def test_primitive_comparison():
4243 def assert_eq(a, b):
4244 assert (a == b) is True
4245 assert (b == a) is True
4246 assert (a != b) is False
4247 assert (b != a) is False
4248 assert (a < b) is False
4249 assert (a <= b) is True
4250 assert (a > b) is False
4251 assert (a >= b) is True
4252 assert (b < a) is False
4253 assert (b <= a) is True
4254 assert (b > a) is False
4255 assert (b >= a) is True
4256 assert hash(a) == hash(b)
4257 def assert_lt(a, b, check_hash=True):
4258 assert (a == b) is False
4259 assert (b == a) is False
4260 assert (a != b) is True
4261 assert (b != a) is True
4262 assert (a < b) is True
4263 assert (a <= b) is True
4264 assert (a > b) is False
4265 assert (a >= b) is False
4266 assert (b < a) is False
4267 assert (b <= a) is False
4268 assert (b > a) is True
4269 assert (b >= a) is True
4270 if check_hash:
4271 assert hash(a) != hash(b) # (or at least, it is unlikely)
4272 def assert_gt(a, b, check_hash=True):
4273 assert_lt(b, a, check_hash)
4274 def assert_ne(a, b):
4275 assert (a == b) is False
4276 assert (b == a) is False
4277 assert (a != b) is True
4278 assert (b != a) is True
4279 if strict_compare:
4280 with pytest.raises(TypeError): a < b
4281 with pytest.raises(TypeError): a <= b
4282 with pytest.raises(TypeError): a > b
4283 with pytest.raises(TypeError): a >= b
4284 with pytest.raises(TypeError): b < a
4285 with pytest.raises(TypeError): b <= a
4286 with pytest.raises(TypeError): b > a
4287 with pytest.raises(TypeError): b >= a
4288 elif a < b:
4289 assert_lt(a, b)
4290 else:
4291 assert_lt(b, a)
4292 assert_eq(5, 5)
4293 assert_lt(3, 5)
4294 assert_ne('5', 5)
4295 #
4296 t1 = new_primitive_type("char")
4297 t2 = new_primitive_type("int")
4298 t3 = new_primitive_type("unsigned char")
4299 t4 = new_primitive_type("unsigned int")
4300 t5 = new_primitive_type("float")
4301 t6 = new_primitive_type("double")
4302 assert_eq(cast(t1, 65), b'A')
4303 assert_lt(cast(t1, 64), b'\x99')
4304 assert_gt(cast(t1, 200), b'A')
4305 assert_ne(cast(t1, 65), 65)
4306 assert_eq(cast(t2, -25), -25)
4307 assert_lt(cast(t2, -25), -24)
4308 assert_gt(cast(t2, -25), -26)
4309 assert_eq(cast(t3, 65), 65)
4310 assert_ne(cast(t3, 65), b'A')
4311 assert_ne(cast(t3, 65), cast(t1, 65))
4312 assert_gt(cast(t4, -1), -1, check_hash=False)
4313 assert_gt(cast(t4, -1), cast(t2, -1), check_hash=False)
4314 assert_gt(cast(t4, -1), 99999)
4315 assert_eq(cast(t4, -1), 256 ** size_of_int() - 1)
4316 assert_eq(cast(t5, 3.0), 3)
4317 assert_eq(cast(t5, 3.5), 3.5)
4318 assert_lt(cast(t5, 3.3), 3.3) # imperfect rounding
4319 assert_eq(cast(t6, 3.3), 3.3)
4320 assert_eq(cast(t5, 3.5), cast(t6, 3.5))
4321 assert_lt(cast(t5, 3.1), cast(t6, 3.1)) # imperfect rounding
4322 assert_eq(cast(t5, 7.0), cast(t3, 7))
4323 assert_lt(cast(t5, 3.1), 3.101)
4324 assert_gt(cast(t5, 3.1), 3)
4325
4326 def test_explicit_release_new():
4327 # release() on a ffi.new() object has no effect on CPython, but
4328 # really releases memory on PyPy. We can't test that effect
4329 # though, because a released cdata is not marked.
4330 BIntP = new_pointer_type(new_primitive_type("int"))
4331 p = newp(BIntP)
4332 p[0] = 42
4333 with pytest.raises(IndexError):
4334 p[1]
4335 release(p)
4336 # here, reading p[0] might give garbage or segfault...
4337 release(p) # no effect
4338 #
4339 BStruct = new_struct_type("struct foo")
4340 BStructP = new_pointer_type(BStruct)
4341 complete_struct_or_union(BStruct, [('p', BIntP, -1)])
4342 pstruct = newp(BStructP)
4343 assert pstruct.p == cast(BIntP, 0)
4344 release(pstruct)
4345 # here, reading pstruct.p might give garbage or segfault...
4346 release(pstruct) # no effect
4347
4348 def test_explicit_release_new_contextmgr():
4349 BIntP = new_pointer_type(new_primitive_type("int"))
4350 with newp(BIntP) as p:
4351 p[0] = 42
4352 assert p[0] == 42
4353 # here, reading p[0] might give garbage or segfault...
4354 release(p) # no effect
4355
4356 def test_explicit_release_badtype():
4357 BIntP = new_pointer_type(new_primitive_type("int"))
4358 p = cast(BIntP, 12345)
4359 pytest.raises(ValueError, release, p)
4360 pytest.raises(ValueError, release, p)
4361 BStruct = new_struct_type("struct foo")
4362 BStructP = new_pointer_type(BStruct)
4363 complete_struct_or_union(BStruct, [('p', BIntP, -1)])
4364 pstruct = newp(BStructP)
4365 pytest.raises(ValueError, release, pstruct[0])
4366
4367 def test_explicit_release_badtype_contextmgr():
4368 BIntP = new_pointer_type(new_primitive_type("int"))
4369 p = cast(BIntP, 12345)
4370 with pytest.raises(ValueError):
4371 with p:
4372 pass
4373 with pytest.raises(ValueError):
4374 with p:
4375 pass
4376
4377 def test_explicit_release_gc():
4378 BIntP = new_pointer_type(new_primitive_type("int"))
4379 seen = []
4380 intp1 = newp(BIntP, 12345)
4381 p1 = cast(BIntP, intp1)
4382 p = gcp(p1, seen.append)
4383 assert seen == []
4384 release(p)
4385 assert seen == [p1]
4386 assert p1[0] == 12345
4387 assert p[0] == 12345 # true so far, but might change to raise RuntimeError
4388 release(p) # no effect
4389
4390 def test_explicit_release_gc_contextmgr():
4391 BIntP = new_pointer_type(new_primitive_type("int"))
4392 seen = []
4393 intp1 = newp(BIntP, 12345)
4394 p1 = cast(BIntP, intp1)
4395 p = gcp(p1, seen.append)
4396 with p:
4397 assert p[0] == 12345
4398 assert seen == []
4399 assert seen == [p1]
4400 assert p1[0] == 12345
4401 assert p[0] == 12345 # true so far, but might change to raise RuntimeError
4402 release(p) # no effect
4403
4404 def test_explicit_release_from_buffer():
4405 a = bytearray(b"xyz")
4406 BChar = new_primitive_type("char")
4407 BCharP = new_pointer_type(BChar)
4408 BCharA = new_array_type(BCharP, None)
4409 p = from_buffer(BCharA, a)
4410 assert p[2] == b"z"
4411 assert repr(p) == "<cdata 'char[]' buffer len 3 from 'bytearray' object>"
4412 release(p)
4413 assert p[2] == b"z" # true so far, but might change to raise RuntimeError
4414 assert repr(p) == "<cdata 'char[]' buffer RELEASED>"
4415 release(p) # no effect
4416
4417 def test_explicit_release_from_buffer_contextmgr():
4418 a = bytearray(b"xyz")
4419 BChar = new_primitive_type("char")
4420 BCharP = new_pointer_type(BChar)
4421 BCharA = new_array_type(BCharP, None)
4422 p = from_buffer(BCharA, a)
4423 with p:
4424 assert p[2] == b"z"
4425 assert p[2] == b"z" # true so far, but might change to raise RuntimeError
4426 assert repr(p) == "<cdata 'char[]' buffer RELEASED>"
4427 release(p) # no effect
4428
4429 def test_explicit_release_bytearray_on_cpython():
4430 if '__pypy__' in sys.builtin_module_names:
4431 pytest.skip("pypy's bytearray are never locked")
4432 a = bytearray(b"xyz")
4433 BChar = new_primitive_type("char")
4434 BCharP = new_pointer_type(BChar)
4435 BCharA = new_array_type(BCharP, None)
4436 a += b't' * 10
4437 p = from_buffer(BCharA, a)
4438 with pytest.raises(BufferError):
4439 a += b'u' * 100
4440 release(p)
4441 a += b'v' * 100
4442 release(p) # no effect
4443 a += b'w' * 1000
4444 assert a == bytearray(b"xyz" + b't' * 10 + b'v' * 100 + b'w' * 1000)
4445
4446 def test_int_doesnt_give_bool():
4447 BBool = new_primitive_type("_Bool")
4448 x = int(cast(BBool, 42))
4449 assert type(x) is int and x == 1
4450 x = long(cast(BBool, 42))
4451 assert type(x) is long and x == 1
4452 with pytest.raises(TypeError):
4453 float(cast(BBool, 42))
4454 with pytest.raises(TypeError):
4455 complex(cast(BBool, 42))
4456
4457 def test_cannot_call_null_function_pointer():
4458 BInt = new_primitive_type("int")
4459 BFunc = new_function_type((BInt, BInt), BInt, False)
4460 f = cast(BFunc, 0)
4461 with pytest.raises(RuntimeError):
4462 f(40, 2)
4463
4464 def test_huge_structure():
4465 BChar = new_primitive_type("char")
4466 BArray = new_array_type(new_pointer_type(BChar), sys.maxsize)
4467 assert sizeof(BArray) == sys.maxsize
4468 BStruct = new_struct_type("struct foo")
4469 complete_struct_or_union(BStruct, [('a1', BArray, -1)])
4470 assert sizeof(BStruct) == sys.maxsize
4471
4472 def test_get_types():
4473 import _cffi_backend
4474 CData, CType = _get_types()
4475 assert CData is _cffi_backend._CDataBase
4476 assert CType is _cffi_backend.CType
4477
4478 def test_type_available_with_correct_names():
4479 import _cffi_backend
4480 check_names = [
4481 'CType',
4482 'CField',
4483 'CLibrary',
4484 '_CDataBase',
4485 'FFI',
4486 'Lib',
4487 'buffer',
4488 ]
4489 if '__pypy__' in sys.builtin_module_names:
4490 check_names += [
4491 '__CData_iterator',
4492 '__FFIGlobSupport',
4493 '__FFIAllocator',
4494 '__FFIFunctionWrapper',
4495 ]
4496 else:
4497 check_names += [
4498 '__CDataOwn',
4499 '__CDataOwnGC',
4500 '__CDataFromBuf',
4501 '__CDataGCP',
4502 '__CData_iterator',
4503 '__FFIGlobSupport',
4504 ]
4505 for name in check_names:
4506 tp = getattr(_cffi_backend, name)
4507 assert isinstance(tp, type)
4508 assert (tp.__module__, tp.__name__) == ('_cffi_backend', name)
4509
4510 def test_unaligned_types():
4511 BByteArray = new_array_type(
4512 new_pointer_type(new_primitive_type("unsigned char")), None)
4513 pbuf = newp(BByteArray, 40)
4514 buf = buffer(pbuf)
4515 #
4516 for name in ['short', 'int', 'long', 'long long', 'float', 'double',
4517 '_cffi_float_complex_t', '_cffi_double_complex_t']:
4518 p = new_primitive_type(name)
4519 if name.endswith('_complex_t'):
4520 num = cast(p, 1.23 - 4.56j)
4521 else:
4522 num = cast(p, 0x0123456789abcdef)
4523 size = sizeof(p)
4524 buf[0:40] = b"\x00" * 40
4525 pbuf1 = cast(new_pointer_type(p), pbuf + 1)
4526 pbuf1[0] = num
4527 assert pbuf1[0] == num
4528 assert buf[0] == b'\x00'
4529 assert buf[1 + size] == b'\x00'