Debian Codegraph @

src/cffi/backend_ctypes.py

raw
1 import ctypes, ctypes.util, operator, sys
2 from . import model
3
4 if sys.version_info < (3,):
5 bytechr = chr
6 else:
7 unicode = str
8 long = int
9 xrange = range
10 bytechr = lambda num: bytes([num])
11
12 class CTypesType(type):
13 pass
14
15 class CTypesData:
16 __metaclass__ = CTypesType
17 __slots__ = ['__weakref__']
18 __name__ = '<cdata>'
19
20 def __init__(self, *args):
21 raise TypeError("cannot instantiate %r" % (self.__class__,))
22
23 @classmethod
24 def _newp(cls, init):
25 raise TypeError("expected a pointer or array ctype, got '%s'"
26 % (cls._get_c_name(),))
27
28 @staticmethod
29 def _to_ctypes(value):
30 raise TypeError
31
32 @classmethod
33 def _arg_to_ctypes(cls, *value):
34 try:
35 ctype = cls._ctype
36 except AttributeError:
37 raise TypeError("cannot create an instance of %r" % (cls,))
38 if value:
39 res = cls._to_ctypes(*value)
40 if not isinstance(res, ctype):
41 res = cls._ctype(res)
42 else:
43 res = cls._ctype()
44 return res
45
46 @classmethod
47 def _create_ctype_obj(cls, init):
48 if init is None:
49 return cls._arg_to_ctypes()
50 else:
51 return cls._arg_to_ctypes(init)
52
53 @staticmethod
54 def _from_ctypes(ctypes_value):
55 raise TypeError
56
57 @classmethod
58 def _get_c_name(cls, replace_with=''):
59 return cls._reftypename.replace(' &', replace_with)
60
61 @classmethod
62 def _fix_class(cls):
63 cls.__name__ = 'CData<%s>' % (cls._get_c_name(),)
64 cls.__qualname__ = 'CData<%s>' % (cls._get_c_name(),)
65 cls.__module__ = 'ffi'
66
67 def _get_own_repr(self):
68 raise NotImplementedError
69
70 def _addr_repr(self, address):
71 if address == 0:
72 return 'NULL'
73 else:
74 if address < 0:
75 address += 1 << (8*ctypes.sizeof(ctypes.c_void_p))
76 return '0x%x' % address
77
78 def __repr__(self, c_name=None):
79 own = self._get_own_repr()
80 return '<cdata %r %s>' % (c_name or self._get_c_name(), own)
81
82 def _convert_to_address(self, BClass):
83 if BClass is None:
84 raise TypeError("cannot convert %r to an address" % (
85 self._get_c_name(),))
86 else:
87 raise TypeError("cannot convert %r to %r" % (
88 self._get_c_name(), BClass._get_c_name()))
89
90 @classmethod
91 def _get_size(cls):
92 return ctypes.sizeof(cls._ctype)
93
94 def _get_size_of_instance(self):
95 return ctypes.sizeof(self._ctype)
96
97 @classmethod
98 def _cast_from(cls, source):
99 raise TypeError("cannot cast to %r" % (cls._get_c_name(),))
100
101 def _cast_to_integer(self):
102 return self._convert_to_address(None)
103
104 @classmethod
105 def _alignment(cls):
106 return ctypes.alignment(cls._ctype)
107
108 def __iter__(self):
109 raise TypeError("cdata %r does not support iteration" % (
110 self._get_c_name()),)
111
112 def _make_cmp(name):
113 cmpfunc = getattr(operator, name)
114 def cmp(self, other):
115 v_is_ptr = not isinstance(self, CTypesGenericPrimitive)
116 w_is_ptr = (isinstance(other, CTypesData) and
117 not isinstance(other, CTypesGenericPrimitive))
118 if v_is_ptr and w_is_ptr:
119 return cmpfunc(self._convert_to_address(None),
120 other._convert_to_address(None))
121 elif v_is_ptr or w_is_ptr:
122 return NotImplemented
123 else:
124 if isinstance(self, CTypesGenericPrimitive):
125 self = self._value
126 if isinstance(other, CTypesGenericPrimitive):
127 other = other._value
128 return cmpfunc(self, other)
129 cmp.func_name = name
130 return cmp
131
132 __eq__ = _make_cmp('__eq__')
133 __ne__ = _make_cmp('__ne__')
134 __lt__ = _make_cmp('__lt__')
135 __le__ = _make_cmp('__le__')
136 __gt__ = _make_cmp('__gt__')
137 __ge__ = _make_cmp('__ge__')
138
139 def __hash__(self):
140 return hash(self._convert_to_address(None))
141
142 def _to_string(self, maxlen):
143 raise TypeError("string(): %r" % (self,))
144
145
146 class CTypesGenericPrimitive(CTypesData):
147 __slots__ = []
148
149 def __hash__(self):
150 return hash(self._value)
151
152 def _get_own_repr(self):
153 return repr(self._from_ctypes(self._value))
154
155
156 class CTypesGenericArray(CTypesData):
157 __slots__ = []
158
159 @classmethod
160 def _newp(cls, init):
161 return cls(init)
162
163 def __iter__(self):
164 for i in xrange(len(self)):
165 yield self[i]
166
167 def _get_own_repr(self):
168 return self._addr_repr(ctypes.addressof(self._blob))
169
170
171 class CTypesGenericPtr(CTypesData):
172 __slots__ = ['_address', '_as_ctype_ptr']
173 _automatic_casts = False
174 kind = "pointer"
175
176 @classmethod
177 def _newp(cls, init):
178 return cls(init)
179
180 @classmethod
181 def _cast_from(cls, source):
182 if source is None:
183 address = 0
184 elif isinstance(source, CTypesData):
185 address = source._cast_to_integer()
186 elif isinstance(source, (int, long)):
187 address = source
188 else:
189 raise TypeError("bad type for cast to %r: %r" %
190 (cls, type(source).__name__))
191 return cls._new_pointer_at(address)
192
193 @classmethod
194 def _new_pointer_at(cls, address):
195 self = cls.__new__(cls)
196 self._address = address
197 self._as_ctype_ptr = ctypes.cast(address, cls._ctype)
198 return self
199
200 def _get_own_repr(self):
201 try:
202 return self._addr_repr(self._address)
203 except AttributeError:
204 return '???'
205
206 def _cast_to_integer(self):
207 return self._address
208
209 def __nonzero__(self):
210 return bool(self._address)
211 __bool__ = __nonzero__
212
213 @classmethod
214 def _to_ctypes(cls, value):
215 if not isinstance(value, CTypesData):
216 raise TypeError("unexpected %s object" % type(value).__name__)
217 address = value._convert_to_address(cls)
218 return ctypes.cast(address, cls._ctype)
219
220 @classmethod
221 def _from_ctypes(cls, ctypes_ptr):
222 address = ctypes.cast(ctypes_ptr, ctypes.c_void_p).value or 0
223 return cls._new_pointer_at(address)
224
225 @classmethod
226 def _initialize(cls, ctypes_ptr, value):
227 if value:
228 ctypes_ptr.contents = cls._to_ctypes(value).contents
229
230 def _convert_to_address(self, BClass):
231 if (BClass in (self.__class__, None) or BClass._automatic_casts
232 or self._automatic_casts):
233 return self._address
234 else:
235 return CTypesData._convert_to_address(self, BClass)
236
237
238 class CTypesBaseStructOrUnion(CTypesData):
239 __slots__ = ['_blob']
240
241 @classmethod
242 def _create_ctype_obj(cls, init):
243 # may be overridden
244 raise TypeError("cannot instantiate opaque type %s" % (cls,))
245
246 def _get_own_repr(self):
247 return self._addr_repr(ctypes.addressof(self._blob))
248
249 @classmethod
250 def _offsetof(cls, fieldname):
251 return getattr(cls._ctype, fieldname).offset
252
253 def _convert_to_address(self, BClass):
254 if getattr(BClass, '_BItem', None) is self.__class__:
255 return ctypes.addressof(self._blob)
256 else:
257 return CTypesData._convert_to_address(self, BClass)
258
259 @classmethod
260 def _from_ctypes(cls, ctypes_struct_or_union):
261 self = cls.__new__(cls)
262 self._blob = ctypes_struct_or_union
263 return self
264
265 @classmethod
266 def _to_ctypes(cls, value):
267 return value._blob
268
269 def __repr__(self, c_name=None):
270 return CTypesData.__repr__(self, c_name or self._get_c_name(' &'))
271
272
273 class CTypesBackend:
274
275 PRIMITIVE_TYPES = {
276 'char': ctypes.c_char,
277 'short': ctypes.c_short,
278 'int': ctypes.c_int,
279 'long': ctypes.c_long,
280 'long long': ctypes.c_longlong,
281 'signed char': ctypes.c_byte,
282 'unsigned char': ctypes.c_ubyte,
283 'unsigned short': ctypes.c_ushort,
284 'unsigned int': ctypes.c_uint,
285 'unsigned long': ctypes.c_ulong,
286 'unsigned long long': ctypes.c_ulonglong,
287 'float': ctypes.c_float,
288 'double': ctypes.c_double,
289 '_Bool': ctypes.c_bool,
290 }
291
292 for _name in ['unsigned long long', 'unsigned long',
293 'unsigned int', 'unsigned short', 'unsigned char']:
294 _size = ctypes.sizeof(PRIMITIVE_TYPES[_name])
295 PRIMITIVE_TYPES['uint%d_t' % (8*_size)] = PRIMITIVE_TYPES[_name]
296 if _size == ctypes.sizeof(ctypes.c_void_p):
297 PRIMITIVE_TYPES['uintptr_t'] = PRIMITIVE_TYPES[_name]
298 if _size == ctypes.sizeof(ctypes.c_size_t):
299 PRIMITIVE_TYPES['size_t'] = PRIMITIVE_TYPES[_name]
300
301 for _name in ['long long', 'long', 'int', 'short', 'signed char']:
302 _size = ctypes.sizeof(PRIMITIVE_TYPES[_name])
303 PRIMITIVE_TYPES['int%d_t' % (8*_size)] = PRIMITIVE_TYPES[_name]
304 if _size == ctypes.sizeof(ctypes.c_void_p):
305 PRIMITIVE_TYPES['intptr_t'] = PRIMITIVE_TYPES[_name]
306 PRIMITIVE_TYPES['ptrdiff_t'] = PRIMITIVE_TYPES[_name]
307 if _size == ctypes.sizeof(ctypes.c_size_t):
308 PRIMITIVE_TYPES['ssize_t'] = PRIMITIVE_TYPES[_name]
309
310
311 def __init__(self):
312 self.RTLD_LAZY = 0 # not supported anyway by ctypes
313 self.RTLD_NOW = 0
314 self.RTLD_GLOBAL = ctypes.RTLD_GLOBAL
315 self.RTLD_LOCAL = ctypes.RTLD_LOCAL
316
317 def set_ffi(self, ffi):
318 self.ffi = ffi
319
320 def _get_types(self):
321 return CTypesData, CTypesType
322
323 def load_library(self, path, flags=0):
324 cdll = ctypes.CDLL(path, flags)
325 return CTypesLibrary(self, cdll)
326
327 def new_void_type(self):
328 class CTypesVoid(CTypesData):
329 __slots__ = []
330 _reftypename = 'void &'
331 @staticmethod
332 def _from_ctypes(novalue):
333 return None
334 @staticmethod
335 def _to_ctypes(novalue):
336 if novalue is not None:
337 raise TypeError("None expected, got %s object" %
338 (type(novalue).__name__,))
339 CTypesVoid._fix_class()
340 return CTypesVoid
341
342 def new_primitive_type(self, name):
343 if name == 'wchar_t':
344 raise NotImplementedError(name)
345 ctype = self.PRIMITIVE_TYPES[name]
346 if name == 'char':
347 kind = 'char'
348 elif name in ('float', 'double'):
349 kind = 'float'
350 else:
351 if name in ('signed char', 'unsigned char'):
352 kind = 'byte'
353 elif name == '_Bool':
354 kind = 'bool'
355 else:
356 kind = 'int'
357 is_signed = (ctype(-1).value == -1)
358 #
359 def _cast_source_to_int(source):
360 if isinstance(source, (int, long, float)):
361 source = int(source)
362 elif isinstance(source, CTypesData):
363 source = source._cast_to_integer()
364 elif isinstance(source, bytes):
365 source = ord(source)
366 elif source is None:
367 source = 0
368 else:
369 raise TypeError("bad type for cast to %r: %r" %
370 (CTypesPrimitive, type(source).__name__))
371 return source
372 #
373 kind1 = kind
374 class CTypesPrimitive(CTypesGenericPrimitive):
375 __slots__ = ['_value']
376 _ctype = ctype
377 _reftypename = '%s &' % name
378 kind = kind1
379
380 def __init__(self, value):
381 self._value = value
382
383 @staticmethod
384 def _create_ctype_obj(init):
385 if init is None:
386 return ctype()
387 return ctype(CTypesPrimitive._to_ctypes(init))
388
389 if kind in {'int', 'byte'}:
390 @classmethod
391 def _cast_from(cls, source):
392 source = _cast_source_to_int(source)
393 source = ctype(source).value # cast within range
394 return cls(source)
395 def __int__(self):
396 return self._value
397
398 if kind == 'bool':
399 @classmethod
400 def _cast_from(cls, source):
401 if not isinstance(source, (int, long, float)):
402 source = _cast_source_to_int(source)
403 return cls(bool(source))
404 def __int__(self):
405 return int(self._value)
406
407 if kind == 'char':
408 @classmethod
409 def _cast_from(cls, source):
410 source = _cast_source_to_int(source)
411 source = bytechr(source & 0xFF)
412 return cls(source)
413 def __int__(self):
414 return ord(self._value)
415
416 if kind == 'float':
417 @classmethod
418 def _cast_from(cls, source):
419 if isinstance(source, float):
420 pass
421 elif isinstance(source, CTypesGenericPrimitive):
422 if hasattr(source, '__float__'):
423 source = float(source)
424 else:
425 source = int(source)
426 else:
427 source = _cast_source_to_int(source)
428 source = ctype(source).value # fix precision
429 return cls(source)
430 def __int__(self):
431 return int(self._value)
432 def __float__(self):
433 return self._value
434
435 _cast_to_integer = __int__
436
437 if kind in {'int', 'byte', 'bool'}:
438 @staticmethod
439 def _to_ctypes(x):
440 if not isinstance(x, (int, long)):
441 if isinstance(x, CTypesData):
442 x = int(x)
443 else:
444 raise TypeError("integer expected, got %s" %
445 type(x).__name__)
446 if ctype(x).value != x:
447 if not is_signed and x < 0:
448 raise OverflowError("%s: negative integer" % name)
449 else:
450 raise OverflowError("%s: integer out of bounds"
451 % name)
452 return x
453
454 if kind == 'char':
455 @staticmethod
456 def _to_ctypes(x):
457 if isinstance(x, bytes) and len(x) == 1:
458 return x
459 if isinstance(x, CTypesPrimitive): # <CData <char>>
460 return x._value
461 raise TypeError("character expected, got %s" %
462 type(x).__name__)
463 def __nonzero__(self):
464 return ord(self._value) != 0
465 else:
466 def __nonzero__(self):
467 return self._value != 0
468 __bool__ = __nonzero__
469
470 if kind == 'float':
471 @staticmethod
472 def _to_ctypes(x):
473 if not isinstance(x, (int, long, float, CTypesData)):
474 raise TypeError("float expected, got %s" %
475 type(x).__name__)
476 return ctype(x).value
477
478 @staticmethod
479 def _from_ctypes(value):
480 return getattr(value, 'value', value)
481
482 @staticmethod
483 def _initialize(blob, init):
484 blob.value = CTypesPrimitive._to_ctypes(init)
485
486 if kind == 'char':
487 def _to_string(self, maxlen):
488 return self._value
489 if kind == 'byte':
490 def _to_string(self, maxlen):
491 return chr(self._value & 0xff)
492 #
493 CTypesPrimitive._fix_class()
494 return CTypesPrimitive
495
496 def new_pointer_type(self, BItem):
497 getbtype = self.ffi._get_cached_btype
498 if BItem is getbtype(model.PrimitiveType('char')):
499 kind = 'charp'
500 elif BItem in (getbtype(model.PrimitiveType('signed char')),
501 getbtype(model.PrimitiveType('unsigned char'))):
502 kind = 'bytep'
503 elif BItem is getbtype(model.void_type):
504 kind = 'voidp'
505 else:
506 kind = 'generic'
507 #
508 class CTypesPtr(CTypesGenericPtr):
509 __slots__ = ['_own']
510 if kind == 'charp':
511 __slots__ += ['__as_strbuf']
512 _BItem = BItem
513 if hasattr(BItem, '_ctype'):
514 _ctype = ctypes.POINTER(BItem._ctype)
515 _bitem_size = ctypes.sizeof(BItem._ctype)
516 else:
517 _ctype = ctypes.c_void_p
518 if issubclass(BItem, CTypesGenericArray):
519 _reftypename = BItem._get_c_name('(* &)')
520 else:
521 _reftypename = BItem._get_c_name(' * &')
522
523 def __init__(self, init):
524 ctypeobj = BItem._create_ctype_obj(init)
525 if kind == 'charp':
526 self.__as_strbuf = ctypes.create_string_buffer(
527 ctypeobj.value + b'\x00')
528 self._as_ctype_ptr = ctypes.cast(
529 self.__as_strbuf, self._ctype)
530 else:
531 self._as_ctype_ptr = ctypes.pointer(ctypeobj)
532 self._address = ctypes.cast(self._as_ctype_ptr,
533 ctypes.c_void_p).value
534 self._own = True
535
536 def __add__(self, other):
537 if isinstance(other, (int, long)):
538 return self._new_pointer_at(self._address +
539 other * self._bitem_size)
540 else:
541 return NotImplemented
542
543 def __sub__(self, other):
544 if isinstance(other, (int, long)):
545 return self._new_pointer_at(self._address -
546 other * self._bitem_size)
547 elif type(self) is type(other):
548 return (self._address - other._address) // self._bitem_size
549 else:
550 return NotImplemented
551
552 def __getitem__(self, index):
553 if getattr(self, '_own', False) and index != 0:
554 raise IndexError
555 return BItem._from_ctypes(self._as_ctype_ptr[index])
556
557 def __setitem__(self, index, value):
558 self._as_ctype_ptr[index] = BItem._to_ctypes(value)
559
560 if kind in {'charp', 'voidp'}:
561 @classmethod
562 def _arg_to_ctypes(cls, *value):
563 if value and isinstance(value[0], bytes):
564 return ctypes.c_char_p(value[0])
565 else:
566 return super()._arg_to_ctypes(*value)
567
568 if kind in {'charp', 'bytep'}:
569 def _to_string(self, maxlen):
570 if maxlen < 0:
571 maxlen = sys.maxsize
572 p = ctypes.cast(self._as_ctype_ptr,
573 ctypes.POINTER(ctypes.c_char))
574 n = 0
575 while n < maxlen and p[n] != b'\x00':
576 n += 1
577 return b''.join([p[i] for i in range(n)])
578
579 def _get_own_repr(self):
580 if getattr(self, '_own', False):
581 return 'owning %d bytes' % (
582 ctypes.sizeof(self._as_ctype_ptr.contents),)
583 return super()._get_own_repr()
584 #
585 if (BItem is self.ffi._get_cached_btype(model.void_type) or
586 BItem is self.ffi._get_cached_btype(model.PrimitiveType('char'))):
587 CTypesPtr._automatic_casts = True
588 #
589 CTypesPtr._fix_class()
590 return CTypesPtr
591
592 def new_array_type(self, CTypesPtr, length):
593 if length is None:
594 brackets = ' &[]'
595 else:
596 brackets = ' &[%d]' % length
597 BItem = CTypesPtr._BItem
598 getbtype = self.ffi._get_cached_btype
599 if BItem is getbtype(model.PrimitiveType('char')):
600 kind = 'char'
601 elif BItem in (getbtype(model.PrimitiveType('signed char')),
602 getbtype(model.PrimitiveType('unsigned char'))):
603 kind = 'byte'
604 else:
605 kind = 'generic'
606 #
607 class CTypesArray(CTypesGenericArray):
608 __slots__ = ['_blob', '_own']
609 if length is not None:
610 _ctype = BItem._ctype * length
611 else:
612 __slots__.append('_ctype')
613 _reftypename = BItem._get_c_name(brackets)
614 _declared_length = length
615 _CTPtr = CTypesPtr
616
617 def __init__(self, init):
618 if length is None:
619 if isinstance(init, (int, long)):
620 len1 = init
621 init = None
622 elif kind == 'char' and isinstance(init, bytes):
623 len1 = len(init) + 1 # extra null
624 else:
625 init = tuple(init)
626 len1 = len(init)
627 self._ctype = BItem._ctype * len1
628 self._blob = self._ctype()
629 self._own = True
630 if init is not None:
631 self._initialize(self._blob, init)
632
633 @staticmethod
634 def _initialize(blob, init):
635 if isinstance(init, bytes):
636 init = [init[i:i+1] for i in range(len(init))]
637 else:
638 if isinstance(init, CTypesGenericArray):
639 if (len(init) != len(blob) or
640 not isinstance(init, CTypesArray)):
641 raise TypeError("length/type mismatch: %s" % (init,))
642 init = tuple(init)
643 if len(init) > len(blob):
644 raise IndexError("too many initializers")
645 addr = ctypes.cast(blob, ctypes.c_void_p).value
646 PTR = ctypes.POINTER(BItem._ctype)
647 itemsize = ctypes.sizeof(BItem._ctype)
648 for i, value in enumerate(init):
649 p = ctypes.cast(addr + i * itemsize, PTR)
650 BItem._initialize(p.contents, value)
651
652 def __len__(self):
653 return len(self._blob)
654
655 def __getitem__(self, index):
656 if not (0 <= index < len(self._blob)):
657 raise IndexError
658 return BItem._from_ctypes(self._blob[index])
659
660 def __setitem__(self, index, value):
661 if not (0 <= index < len(self._blob)):
662 raise IndexError
663 self._blob[index] = BItem._to_ctypes(value)
664
665 if kind in {'char', 'byte'}:
666 def _to_string(self, maxlen):
667 if maxlen < 0:
668 maxlen = len(self._blob)
669 p = ctypes.cast(self._blob,
670 ctypes.POINTER(ctypes.c_char))
671 n = 0
672 while n < maxlen and p[n] != b'\x00':
673 n += 1
674 return b''.join([p[i] for i in range(n)])
675
676 def _get_own_repr(self):
677 if getattr(self, '_own', False):
678 return 'owning %d bytes' % (ctypes.sizeof(self._blob),)
679 return super()._get_own_repr()
680
681 def _convert_to_address(self, BClass):
682 if BClass in (CTypesPtr, None) or BClass._automatic_casts:
683 return ctypes.addressof(self._blob)
684 else:
685 return CTypesData._convert_to_address(self, BClass)
686
687 @staticmethod
688 def _from_ctypes(ctypes_array):
689 self = CTypesArray.__new__(CTypesArray)
690 self._blob = ctypes_array
691 return self
692
693 @staticmethod
694 def _arg_to_ctypes(value):
695 return CTypesPtr._arg_to_ctypes(value)
696
697 def __add__(self, other):
698 if isinstance(other, (int, long)):
699 return CTypesPtr._new_pointer_at(
700 ctypes.addressof(self._blob) +
701 other * ctypes.sizeof(BItem._ctype))
702 else:
703 return NotImplemented
704
705 @classmethod
706 def _cast_from(cls, source):
707 raise NotImplementedError("casting to %r" % (
708 cls._get_c_name(),))
709 #
710 CTypesArray._fix_class()
711 return CTypesArray
712
713 def _new_struct_or_union(self, kind, name, base_ctypes_class):
714 #
715 class struct_or_union(base_ctypes_class):
716 pass
717 struct_or_union.__name__ = '%s_%s' % (kind, name)
718 kind1 = kind
719 #
720 class CTypesStructOrUnion(CTypesBaseStructOrUnion):
721 __slots__ = ['_blob']
722 _ctype = struct_or_union
723 _reftypename = '%s &' % (name,)
724 _kind = kind = kind1
725 #
726 CTypesStructOrUnion._fix_class()
727 return CTypesStructOrUnion
728
729 def new_struct_type(self, name):
730 return self._new_struct_or_union('struct', name, ctypes.Structure)
731
732 def new_union_type(self, name):
733 return self._new_struct_or_union('union', name, ctypes.Union)
734
735 def complete_struct_or_union(self, CTypesStructOrUnion, fields, tp,
736 totalsize=-1, totalalignment=-1, sflags=0,
737 pack=0):
738 if totalsize >= 0 or totalalignment >= 0:
739 raise NotImplementedError("the ctypes backend of CFFI does not support "
740 "structures completed by verify(); please "
741 "compile and install the _cffi_backend module.")
742 struct_or_union = CTypesStructOrUnion._ctype
743 fnames = [fname for (fname, BField, bitsize) in fields]
744 btypes = [BField for (fname, BField, bitsize) in fields]
745 bitfields = [bitsize for (fname, BField, bitsize) in fields]
746 #
747 bfield_types = {}
748 cfields = []
749 for (fname, BField, bitsize) in fields:
750 if bitsize < 0:
751 cfields.append((fname, BField._ctype))
752 bfield_types[fname] = BField
753 else:
754 cfields.append((fname, BField._ctype, bitsize))
755 bfield_types[fname] = Ellipsis
756 if sflags & 8:
757 struct_or_union._pack_ = 1
758 elif pack:
759 struct_or_union._pack_ = pack
760 struct_or_union._fields_ = cfields
761 CTypesStructOrUnion._bfield_types = bfield_types
762 #
763 @staticmethod
764 def _create_ctype_obj(init):
765 result = struct_or_union()
766 if init is not None:
767 initialize(result, init)
768 return result
769 CTypesStructOrUnion._create_ctype_obj = _create_ctype_obj
770 #
771 def initialize(blob, init):
772 if is_union:
773 if len(init) > 1:
774 raise ValueError("union initializer: %d items given, but "
775 "only one supported (use a dict if needed)"
776 % (len(init),))
777 if not isinstance(init, dict):
778 if isinstance(init, (bytes, unicode)):
779 raise TypeError("union initializer: got a str")
780 init = tuple(init)
781 if len(init) > len(fnames):
782 raise ValueError("too many values for %s initializer" %
783 CTypesStructOrUnion._get_c_name())
784 init = dict(zip(fnames, init))
785 addr = ctypes.addressof(blob)
786 for fname, value in init.items():
787 BField, bitsize = name2fieldtype[fname]
788 assert bitsize < 0, \
789 "not implemented: initializer with bit fields"
790 offset = CTypesStructOrUnion._offsetof(fname)
791 PTR = ctypes.POINTER(BField._ctype)
792 p = ctypes.cast(addr + offset, PTR)
793 BField._initialize(p.contents, value)
794 is_union = CTypesStructOrUnion._kind == 'union'
795 name2fieldtype = dict(zip(fnames, zip(btypes, bitfields)))
796 #
797 for fname, BField, bitsize in fields:
798 if fname == '':
799 raise NotImplementedError("nested anonymous structs/unions")
800 if hasattr(CTypesStructOrUnion, fname):
801 raise ValueError("the field name %r conflicts in "
802 "the ctypes backend" % fname)
803 if bitsize < 0:
804 def getter(self, fname=fname, BField=BField,
805 offset=CTypesStructOrUnion._offsetof(fname),
806 PTR=ctypes.POINTER(BField._ctype)):
807 addr = ctypes.addressof(self._blob)
808 p = ctypes.cast(addr + offset, PTR)
809 return BField._from_ctypes(p.contents)
810 def setter(self, value, fname=fname, BField=BField):
811 setattr(self._blob, fname, BField._to_ctypes(value))
812 #
813 if issubclass(BField, CTypesGenericArray):
814 setter = None
815 if BField._declared_length == 0:
816 def getter(self, fname=fname, BFieldPtr=BField._CTPtr,
817 offset=CTypesStructOrUnion._offsetof(fname),
818 PTR=ctypes.POINTER(BField._ctype)):
819 addr = ctypes.addressof(self._blob)
820 p = ctypes.cast(addr + offset, PTR)
821 return BFieldPtr._from_ctypes(p)
822 #
823 else:
824 def getter(self, fname=fname, BField=BField):
825 return BField._from_ctypes(getattr(self._blob, fname))
826 def setter(self, value, fname=fname, BField=BField):
827 # xxx obscure workaround
828 value = BField._to_ctypes(value)
829 oldvalue = getattr(self._blob, fname)
830 setattr(self._blob, fname, value)
831 if value != getattr(self._blob, fname):
832 setattr(self._blob, fname, oldvalue)
833 raise OverflowError("value too large for bitfield")
834 setattr(CTypesStructOrUnion, fname, property(getter, setter))
835 #
836 CTypesPtr = self.ffi._get_cached_btype(model.PointerType(tp))
837 for fname in fnames:
838 if hasattr(CTypesPtr, fname):
839 raise ValueError("the field name %r conflicts in "
840 "the ctypes backend" % fname)
841 def getter(self, fname=fname):
842 return getattr(self[0], fname)
843 def setter(self, value, fname=fname):
844 setattr(self[0], fname, value)
845 setattr(CTypesPtr, fname, property(getter, setter))
846
847 def new_function_type(self, BArgs, BResult, has_varargs):
848 nameargs = [BArg._get_c_name() for BArg in BArgs]
849 if has_varargs:
850 nameargs.append('...')
851 nameargs = ', '.join(nameargs)
852 #
853 class CTypesFunctionPtr(CTypesGenericPtr):
854 __slots__ = ['_own_callback', '_name']
855 _ctype = ctypes.CFUNCTYPE(getattr(BResult, '_ctype', None),
856 *[BArg._ctype for BArg in BArgs],
857 use_errno=True)
858 _reftypename = BResult._get_c_name('(* &)(%s)' % (nameargs,))
859
860 def __init__(self, init, error=None):
861 # create a callback to the Python callable init()
862 import traceback
863 assert not has_varargs, "varargs not supported for callbacks"
864 if getattr(BResult, '_ctype', None) is not None:
865 error = BResult._from_ctypes(
866 BResult._create_ctype_obj(error))
867 else:
868 error = None
869 def callback(*args):
870 args2 = []
871 for arg, BArg in zip(args, BArgs):
872 args2.append(BArg._from_ctypes(arg))
873 try:
874 res2 = init(*args2)
875 res2 = BResult._to_ctypes(res2)
876 except:
877 traceback.print_exc()
878 res2 = error
879 if issubclass(BResult, CTypesGenericPtr):
880 if res2:
881 res2 = ctypes.cast(res2, ctypes.c_void_p).value
882 # .value: http://bugs.python.org/issue1574593
883 else:
884 res2 = None
885 #print repr(res2)
886 return res2
887 if issubclass(BResult, CTypesGenericPtr):
888 # The only pointers callbacks can return are void*s:
889 # http://bugs.python.org/issue5710
890 callback_ctype = ctypes.CFUNCTYPE(
891 ctypes.c_void_p,
892 *[BArg._ctype for BArg in BArgs],
893 use_errno=True)
894 else:
895 callback_ctype = CTypesFunctionPtr._ctype
896 self._as_ctype_ptr = callback_ctype(callback)
897 self._address = ctypes.cast(self._as_ctype_ptr,
898 ctypes.c_void_p).value
899 self._own_callback = init
900
901 @staticmethod
902 def _initialize(ctypes_ptr, value):
903 if value:
904 raise NotImplementedError("ctypes backend: not supported: "
905 "initializers for function pointers")
906
907 def __repr__(self):
908 c_name = getattr(self, '_name', None)
909 if c_name:
910 i = self._reftypename.index('(* &)')
911 if self._reftypename[i-1] not in ' )*':
912 c_name = ' ' + c_name
913 c_name = self._reftypename.replace('(* &)', c_name)
914 return CTypesData.__repr__(self, c_name)
915
916 def _get_own_repr(self):
917 if getattr(self, '_own_callback', None) is not None:
918 return 'calling %r' % (self._own_callback,)
919 return super()._get_own_repr()
920
921 def __call__(self, *args):
922 if has_varargs:
923 assert len(args) >= len(BArgs)
924 extraargs = args[len(BArgs):]
925 args = args[:len(BArgs)]
926 else:
927 assert len(args) == len(BArgs)
928 ctypes_args = []
929 for arg, BArg in zip(args, BArgs):
930 ctypes_args.append(BArg._arg_to_ctypes(arg))
931 if has_varargs:
932 for i, arg in enumerate(extraargs):
933 if arg is None:
934 ctypes_args.append(ctypes.c_void_p(0)) # NULL
935 continue
936 if not isinstance(arg, CTypesData):
937 raise TypeError(
938 "argument %d passed in the variadic part "
939 "needs to be a cdata object (got %s)" %
940 (1 + len(BArgs) + i, type(arg).__name__))
941 ctypes_args.append(arg._arg_to_ctypes(arg))
942 result = self._as_ctype_ptr(*ctypes_args)
943 return BResult._from_ctypes(result)
944 #
945 CTypesFunctionPtr._fix_class()
946 return CTypesFunctionPtr
947
948 def new_enum_type(self, name, enumerators, enumvalues, CTypesInt):
949 assert isinstance(name, str)
950 reverse_mapping = dict(zip(reversed(enumvalues),
951 reversed(enumerators)))
952 #
953 class CTypesEnum(CTypesInt):
954 __slots__ = []
955 _reftypename = '%s &' % name
956
957 def _get_own_repr(self):
958 value = self._value
959 try:
960 return '%d: %s' % (value, reverse_mapping[value])
961 except KeyError:
962 return str(value)
963
964 def _to_string(self, maxlen):
965 value = self._value
966 try:
967 return reverse_mapping[value]
968 except KeyError:
969 return str(value)
970 #
971 CTypesEnum._fix_class()
972 return CTypesEnum
973
974 def get_errno(self):
975 return ctypes.get_errno()
976
977 def set_errno(self, value):
978 ctypes.set_errno(value)
979
980 def string(self, b, maxlen=-1):
981 return b._to_string(maxlen)
982
983 def buffer(self, bptr, size=-1):
984 raise NotImplementedError("buffer() with ctypes backend")
985
986 def sizeof(self, cdata_or_BType):
987 if isinstance(cdata_or_BType, CTypesData):
988 return cdata_or_BType._get_size_of_instance()
989 else:
990 assert issubclass(cdata_or_BType, CTypesData)
991 return cdata_or_BType._get_size()
992
993 def alignof(self, BType):
994 assert issubclass(BType, CTypesData)
995 return BType._alignment()
996
997 def newp(self, BType, source):
998 if not issubclass(BType, CTypesData):
999 raise TypeError
1000 return BType._newp(source)
1001
1002 def cast(self, BType, source):
1003 return BType._cast_from(source)
1004
1005 def callback(self, BType, source, error, onerror):
1006 assert onerror is None # XXX not implemented
1007 return BType(source, error)
1008
1009 _weakref_cache_ref = None
1010
1011 def gcp(self, cdata, destructor, size=0):
1012 if self._weakref_cache_ref is None:
1013 import weakref
1014 class MyRef(weakref.ref):
1015 def __eq__(self, other):
1016 myref = self()
1017 return self is other or (
1018 myref is not None and myref is other())
1019 def __ne__(self, other):
1020 return not (self == other)
1021 def __hash__(self):
1022 try:
1023 return self._hash
1024 except AttributeError:
1025 self._hash = hash(self())
1026 return self._hash
1027 self._weakref_cache_ref = {}, MyRef
1028 weak_cache, MyRef = self._weakref_cache_ref
1029
1030 if destructor is None:
1031 try:
1032 del weak_cache[MyRef(cdata)]
1033 except KeyError:
1034 raise TypeError("Can remove destructor only on a object "
1035 "previously returned by ffi.gc()")
1036 return None
1037
1038 def remove(k):
1039 cdata, destructor = weak_cache.pop(k, (None, None))
1040 if destructor is not None:
1041 destructor(cdata)
1042
1043 new_cdata = self.cast(self.typeof(cdata), cdata)
1044 assert new_cdata is not cdata
1045 weak_cache[MyRef(new_cdata, remove)] = (cdata, destructor)
1046 return new_cdata
1047
1048 typeof = type
1049
1050 def getcname(self, BType, replace_with):
1051 return BType._get_c_name(replace_with)
1052
1053 def typeoffsetof(self, BType, fieldname, num=0):
1054 if isinstance(fieldname, str):
1055 if num == 0 and issubclass(BType, CTypesGenericPtr):
1056 BType = BType._BItem
1057 if not issubclass(BType, CTypesBaseStructOrUnion):
1058 raise TypeError("expected a struct or union ctype")
1059 BField = BType._bfield_types[fieldname]
1060 if BField is Ellipsis:
1061 raise TypeError("not supported for bitfields")
1062 return (BField, BType._offsetof(fieldname))
1063 elif isinstance(fieldname, (int, long)):
1064 if issubclass(BType, CTypesGenericArray):
1065 BType = BType._CTPtr
1066 if not issubclass(BType, CTypesGenericPtr):
1067 raise TypeError("expected an array or ptr ctype")
1068 BItem = BType._BItem
1069 offset = BItem._get_size() * fieldname
1070 if offset > sys.maxsize:
1071 raise OverflowError
1072 return (BItem, offset)
1073 else:
1074 raise TypeError(type(fieldname))
1075
1076 def rawaddressof(self, BTypePtr, cdata, offset=None):
1077 if isinstance(cdata, CTypesBaseStructOrUnion):
1078 ptr = ctypes.pointer(type(cdata)._to_ctypes(cdata))
1079 elif isinstance(cdata, CTypesGenericPtr):
1080 if offset is None or not issubclass(type(cdata)._BItem,
1081 CTypesBaseStructOrUnion):
1082 raise TypeError("unexpected cdata type")
1083 ptr = type(cdata)._to_ctypes(cdata)
1084 elif isinstance(cdata, CTypesGenericArray):
1085 ptr = type(cdata)._to_ctypes(cdata)
1086 else:
1087 raise TypeError("expected a <cdata 'struct-or-union'>")
1088 if offset:
1089 ptr = ctypes.cast(
1090 ctypes.c_void_p(
1091 ctypes.cast(ptr, ctypes.c_void_p).value + offset),
1092 type(ptr))
1093 return BTypePtr._from_ctypes(ptr)
1094
1095
1096 class CTypesLibrary:
1097
1098 def __init__(self, backend, cdll):
1099 self.backend = backend
1100 self.cdll = cdll
1101
1102 def load_function(self, BType, name):
1103 c_func = getattr(self.cdll, name)
1104 funcobj = BType._from_ctypes(c_func)
1105 funcobj._name = name
1106 return funcobj
1107
1108 def read_variable(self, BType, name):
1109 try:
1110 ctypes_obj = BType._ctype.in_dll(self.cdll, name)
1111 except AttributeError as e:
1112 raise NotImplementedError(e)
1113 return BType._from_ctypes(ctypes_obj)
1114
1115 def write_variable(self, BType, name, value):
1116 new_ctypes_obj = BType._to_ctypes(value)
1117 ctypes_obj = BType._ctype.in_dll(self.cdll, name)
1118 ctypes.memmove(ctypes.addressof(ctypes_obj),
1119 ctypes.addressof(new_ctypes_obj),
1120 ctypes.sizeof(BType._ctype))