Debian Codegraph @

pypy/module/_cffi_backend/cdataobj.py

raw symbols SCIP
1 import operator
2
3 from pypy.interpreter.baseobjspace import W_Root
4 from pypy.interpreter.error import OperationError, oefmt
5 from pypy.interpreter.gateway import interp2app
6 from pypy.interpreter.typedef import TypeDef, make_weakref_descr
7
8 from rpython.rlib import rgc
9 from rpython.rlib.objectmodel import keepalive_until_here, specialize
10 from rpython.rtyper.lltypesystem import lltype, rffi
11 from rpython.tool.sourcetools import func_with_new_name
12
13 from pypy.module._cffi_backend import misc
14
15
16 class W_CData(W_Root):
17 _attrs_ = ['space', '_ptr', 'ctype', '_lifeline_']
18 _immutable_fields_ = ['_ptr', 'ctype']
19 _ptr = lltype.nullptr(rffi.CCHARP.TO)
20
21 def __init__(self, space, ptr, ctype):
22 from pypy.module._cffi_backend import ctypeobj
23 assert lltype.typeOf(ptr) == rffi.CCHARP
24 assert isinstance(ctype, ctypeobj.W_CType)
25 self.space = space
26 self._ptr = ptr # don't access directly! use "with cdata as ptr:"
27 self.ctype = ctype
28
29 def __enter__(self):
30 """Use 'with cdata as ptr:' to access the raw memory. It will
31 stay alive at least until the end of the 'with' block.
32 """
33 return self._ptr
34
35 def __exit__(self, *args):
36 keepalive_until_here(self)
37
38 def unsafe_escaping_ptr(self):
39 """Generally unsafe: escape the pointer to raw memory.
40 If 'self' is a subclass that frees the pointer in a destructor,
41 it may be freed under your feet at any time.
42 """
43 return self._ptr
44
45 def _repr_extra(self):
46 with self as ptr:
47 extra = self.ctype.extra_repr(ptr)
48 return extra
49
50 def _repr_extra_owning(self):
51 from pypy.module._cffi_backend.ctypeptr import W_CTypePointer
52 ctype = self.ctype
53 if isinstance(ctype, W_CTypePointer):
54 num_bytes = ctype.ctitem.size
55 else:
56 num_bytes = self._sizeof()
57 return 'owning %d bytes' % num_bytes
58
59 def repr(self):
60 extra2 = self._repr_extra()
61 extra1 = ''
62 if not isinstance(self, W_CDataNewOwning):
63 # it's slightly confusing to get "<cdata 'struct foo' 0x...>"
64 # because the struct foo is not owned. Trying to make it
65 # clearer, write in this case "<cdata 'struct foo &' 0x...>".
66 from pypy.module._cffi_backend import ctypestruct
67 if isinstance(self.ctype, ctypestruct.W_CTypeStructOrUnion):
68 extra1 = ' &'
69 return self.space.newtext("<cdata '%s%s' %s>" % (
70 self.ctype.name, extra1, extra2))
71
72 def bool(self):
73 with self as ptr:
74 nonzero = self.ctype.nonzero(ptr)
75 return self.space.newbool(nonzero)
76
77 def int(self, space):
78 with self as ptr:
79 w_result = self.ctype.cast_to_int(ptr)
80 return w_result
81
82 def float(self):
83 with self as ptr:
84 w_result = self.ctype.float(ptr)
85 return w_result
86
87 def complex(self):
88 with self as ptr:
89 w_result = self.ctype.complex(ptr)
90 return w_result
91
92 def len(self):
93 from pypy.module._cffi_backend import ctypearray
94 space = self.space
95 if isinstance(self.ctype, ctypearray.W_CTypeArray):
96 return space.newint(self.get_array_length())
97 raise oefmt(space.w_TypeError,
98 "cdata of type '%s' has no len()", self.ctype.name)
99
100 def _compare_mode(self, w_other):
101 from pypy.module._cffi_backend.ctypeprim import W_CTypePrimitive
102 zero = rffi.cast(lltype.Unsigned, 0)
103 self_is_ptr = not isinstance(self.ctype, W_CTypePrimitive)
104 other_is_ptr = (isinstance(w_other, W_CData) and
105 not isinstance(w_other.ctype, W_CTypePrimitive))
106 if other_is_ptr and self_is_ptr:
107 with self as ptr1, w_other as ptr2:
108 ptr1 = rffi.cast(lltype.Unsigned, ptr1)
109 ptr2 = rffi.cast(lltype.Unsigned, ptr2)
110 return (0, ptr1, ptr2, None, None)
111 elif other_is_ptr or self_is_ptr:
112 return (-1, zero, zero, None, None)
113 else:
114 w_ob1 = self.convert_to_object()
115 if isinstance(w_other, W_CData):
116 w_ob2 = w_other.convert_to_object()
117 else:
118 w_ob2 = w_other
119 return (1, zero, zero, w_ob1, w_ob2)
120
121 def _make_comparison(name):
122 op = getattr(operator, name)
123 #
124 def _cmp(self, w_other):
125 space = self.space
126 mode, adr1, adr2, w_ob1, w_ob2 = self._compare_mode(w_other)
127 if mode == 0:
128 return space.newbool(op(adr1, adr2))
129 elif mode == 1:
130 return getattr(space, name)(w_ob1, w_ob2)
131 else:
132 return space.w_NotImplemented
133 #
134 return func_with_new_name(_cmp, name)
135
136 lt = _make_comparison('lt')
137 le = _make_comparison('le')
138 eq = _make_comparison('eq')
139 ne = _make_comparison('ne')
140 gt = _make_comparison('gt')
141 ge = _make_comparison('ge')
142
143 def hash(self):
144 from pypy.module._cffi_backend.ctypeprim import W_CTypePrimitive
145 if isinstance(self.ctype, W_CTypePrimitive):
146 w_ob = self.convert_to_object()
147 if not isinstance(w_ob, W_CData):
148 return self.space.hash(w_ob)
149 ptr = self.unsafe_escaping_ptr()
150 h = rffi.cast(lltype.Signed, ptr)
151 # To hash pointers in dictionaries. Assumes that h shows some
152 # alignment (to 4, 8, maybe 16 bytes), so we use the following
153 # formula to avoid the trailing bits being always 0.
154 h = h ^ (h >> 4)
155 return self.space.newint(h)
156
157 def getitem(self, w_index):
158 space = self.space
159 if space.isinstance_w(w_index, space.w_slice):
160 w_o = self._do_getslice(w_index)
161 else:
162 i = space.getindex_w(w_index, space.w_IndexError)
163 ctype = self.ctype._check_subscript_index(self, i)
164 w_o = self._do_getitem(ctype, i)
165 return w_o
166
167 def _do_getitem(self, ctype, i):
168 ctitem = ctype.ctitem
169 with self as ptr:
170 return ctitem.convert_to_object(
171 rffi.ptradd(ptr, i * ctitem.size))
172
173 def setitem(self, w_index, w_value):
174 space = self.space
175 if space.isinstance_w(w_index, space.w_slice):
176 with self as ptr:
177 self._do_setslice(w_index, w_value, ptr)
178 else:
179 i = space.getindex_w(w_index, space.w_IndexError)
180 ctype = self.ctype._check_subscript_index(self, i)
181 ctitem = ctype.ctitem
182 with self as ptr:
183 ctitem.convert_from_object(
184 rffi.ptradd(ptr, i * ctitem.size),
185 w_value)
186
187 def _do_getslicearg(self, w_slice):
188 from pypy.module._cffi_backend.ctypeptr import W_CTypePointer
189 from pypy.objspace.std.sliceobject import W_SliceObject
190 assert isinstance(w_slice, W_SliceObject)
191 space = self.space
192 #
193 if space.is_w(w_slice.w_start, space.w_None):
194 raise oefmt(space.w_IndexError, "slice start must be specified")
195 start = space.int_w(w_slice.w_start)
196 #
197 if space.is_w(w_slice.w_stop, space.w_None):
198 raise oefmt(space.w_IndexError, "slice stop must be specified")
199 stop = space.int_w(w_slice.w_stop)
200 #
201 if not space.is_w(w_slice.w_step, space.w_None):
202 raise oefmt(space.w_IndexError, "slice with step not supported")
203 #
204 if start > stop:
205 raise oefmt(space.w_IndexError, "slice start > stop")
206 #
207 ctype = self.ctype._check_slice_index(self, start, stop)
208 assert isinstance(ctype, W_CTypePointer)
209 #
210 return ctype, start, stop - start
211
212 def _do_getslice(self, w_slice):
213 ctptr, start, length = self._do_getslicearg(w_slice)
214 #
215 space = self.space
216 ctarray = ctptr.cache_array_type
217 if ctarray is None:
218 from pypy.module._cffi_backend import newtype
219 ctarray = newtype.new_array_type(space, ctptr, space.w_None)
220 ctptr.cache_array_type = ctarray
221 #
222 ptr = self.unsafe_escaping_ptr()
223 ptr = rffi.ptradd(ptr, start * ctarray.ctitem.size)
224 return W_CDataSliced(space, ptr, ctarray, length)
225
226 def _do_setslice(self, w_slice, w_value, ptr):
227 ctptr, start, length = self._do_getslicearg(w_slice)
228 ctitem = ctptr.ctitem
229 ctitemsize = ctitem.size
230 target = rffi.ptradd(ptr, start * ctitemsize)
231 #
232 if isinstance(w_value, W_CData):
233 from pypy.module._cffi_backend import ctypearray
234 ctv = w_value.ctype
235 if (isinstance(ctv, ctypearray.W_CTypeArray) and
236 ctv.ctitem is ctitem and
237 w_value.get_array_length() == length):
238 # fast path: copying from exactly the correct type
239 with w_value as source:
240 source = rffi.cast(rffi.CONST_VOIDP, source)
241 target = rffi.cast(rffi.VOIDP, target)
242 size = rffi.cast(rffi.SIZE_T, ctitemsize * length)
243 rffi.c_memcpy(target, source, size)
244 return
245 #
246 # A fast path for <char[]>[0:N] = "somestring" or some bytearray.
247 from pypy.module._cffi_backend import ctypeprim
248 space = self.space
249 if isinstance(ctitem, ctypeprim.W_CTypePrimitive) and ctitem.size == 1:
250 if space.isinstance_w(w_value, space.w_bytes):
251 from rpython.rtyper.annlowlevel import llstr
252 from rpython.rtyper.lltypesystem.rstr import copy_string_to_raw
253 value = space.bytes_w(w_value)
254 if len(value) != length:
255 raise oefmt(space.w_ValueError,
256 "need a string of length %d, got %d",
257 length, len(value))
258 copy_string_to_raw(llstr(value), target, 0, length)
259 return
260 if space.isinstance_w(w_value, space.w_bytearray):
261 value = w_value.bytearray_list_of_chars_w(space)
262 if len(value) != length:
263 raise oefmt(space.w_ValueError,
264 "need a bytearray of length %d, got %d",
265 length, len(value))
266 self._copy_list_of_chars_to_raw(value, target, length)
267 return
268 #
269 self._do_setslice_iterate(space, ctitem, w_value, target, ctitemsize,
270 length)
271
272 @staticmethod
273 def _do_setslice_iterate(space, ctitem, w_value, target, ctitemsize,
274 length):
275 # general case, contains a loop
276 # (XXX is it worth adding a jitdriver here?)
277 w_iter = space.iter(w_value)
278 for i in range(length):
279 try:
280 w_item = space.next(w_iter)
281 except OperationError as e:
282 if not e.match(space, space.w_StopIteration):
283 raise
284 raise oefmt(space.w_ValueError,
285 "need %d values to unpack, got %d", length, i)
286 ctitem.convert_from_object(target, w_item)
287 target = rffi.ptradd(target, ctitemsize)
288 try:
289 space.next(w_iter)
290 except OperationError as e:
291 if not e.match(space, space.w_StopIteration):
292 raise
293 else:
294 raise oefmt(space.w_ValueError,
295 "got more than %d values to unpack", length)
296
297 @staticmethod
298 def _copy_list_of_chars_to_raw(value, target, length):
299 # contains a loop, moved out of _do_setslice()
300 for i in range(length):
301 target[i] = value[i]
302
303 def _add_or_sub(self, w_other, sign):
304 space = self.space
305 i = sign * space.getindex_w(w_other, space.w_OverflowError)
306 ptr = self.unsafe_escaping_ptr()
307 return self.ctype.add(ptr, i)
308
309 def add(self, w_other):
310 return self._add_or_sub(w_other, +1)
311
312 def sub(self, w_other):
313 space = self.space
314 if isinstance(w_other, W_CData):
315 from pypy.module._cffi_backend import ctypeptr, ctypearray
316 ct = w_other.ctype
317 if isinstance(ct, ctypearray.W_CTypeArray):
318 ct = ct.ctptr
319 #
320 if (ct is not self.ctype or
321 not isinstance(ct, ctypeptr.W_CTypePointer) or
322 (ct.ctitem.size <= 0 and not ct.is_void_ptr)):
323 raise oefmt(space.w_TypeError,
324 "cannot subtract cdata '%s' and cdata '%s'",
325 self.ctype.name, ct.name)
326 #
327 itemsize = ct.ctitem.size
328 with self as ptr1, w_other as ptr2:
329 diff = (rffi.cast(lltype.Signed, ptr1) -
330 rffi.cast(lltype.Signed, ptr2))
331 if itemsize > 1:
332 if diff % itemsize:
333 raise oefmt(space.w_ValueError,
334 "pointer subtraction: the distance between the two "
335 "pointers is not a multiple of the item size")
336 diff //= itemsize
337 return space.newint(diff)
338 #
339 return self._add_or_sub(w_other, -1)
340
341 def getcfield(self, w_attr, mode):
342 space = self.space
343 attr = space.text_w(w_attr)
344 try:
345 cfield = self.ctype.getcfield(attr)
346 except KeyError:
347 raise oefmt(space.w_AttributeError, "cdata '%s' has no field '%s'",
348 self.ctype.name, attr)
349 if cfield is None:
350 raise oefmt(space.w_AttributeError,
351 "cdata '%s' points to an opaque type: cannot %s fields",
352 self.ctype.name, mode)
353 return cfield
354
355 def getattr(self, w_attr):
356 cfield = self.getcfield(w_attr, mode="read")
357 with self as ptr:
358 w_res = cfield.read(ptr, self)
359 return w_res
360
361 def setattr(self, w_attr, w_value):
362 cfield = self.getcfield(w_attr, mode="write")
363 with self as ptr:
364 cfield.write(ptr, w_value)
365
366 def call(self, args_w):
367 with self as ptr:
368 w_result = self.ctype.call(ptr, args_w)
369 return w_result
370
371 def iter(self):
372 return self.ctype.iter(self)
373
374 def unpackiterable_int(self, space):
375 from pypy.module._cffi_backend import ctypearray
376 ctype = self.ctype
377 if isinstance(ctype, ctypearray.W_CTypeArray):
378 length = self.get_array_length()
379 with self as ptr:
380 return ctype.ctitem.unpack_list_of_int_items(ptr, length)
381 return None
382
383 def unpackiterable_float(self, space):
384 from pypy.module._cffi_backend import ctypearray
385 ctype = self.ctype
386 if isinstance(ctype, ctypearray.W_CTypeArray):
387 length = self.get_array_length()
388 with self as ptr:
389 return ctype.ctitem.unpack_list_of_float_items(ptr, length)
390 return None
391
392 @specialize.argtype(1)
393 def write_raw_signed_data(self, source):
394 with self as ptr:
395 misc.write_raw_signed_data(ptr, source, self.ctype.size)
396
397 @specialize.argtype(1)
398 def write_raw_unsigned_data(self, source):
399 with self as ptr:
400 misc.write_raw_unsigned_data(ptr, source, self.ctype.size)
401
402 def write_raw_float_data(self, source):
403 with self as ptr:
404 misc.write_raw_float_data(ptr, source, self.ctype.size)
405
406 def write_raw_complex_data(self, real, imag):
407 with self as ptr:
408 halfsize = self.ctype.size >> 1
409 ptr2 = rffi.ptradd(ptr, halfsize)
410 misc.write_raw_float_data(ptr, real, halfsize)
411 misc.write_raw_float_data(ptr2, imag, halfsize)
412
413 def convert_to_object(self):
414 with self as ptr:
415 w_obj = self.ctype.convert_to_object(ptr)
416 return w_obj
417
418 def get_array_length(self):
419 from pypy.module._cffi_backend import ctypearray
420 ctype = self.ctype
421 assert isinstance(ctype, ctypearray.W_CTypeArray)
422 length = ctype.length
423 assert length >= 0
424 return length
425
426 def _sizeof(self):
427 return self.ctype.size
428
429 def with_gc(self, w_destructor, size=0):
430 space = self.space
431 if space.is_none(w_destructor):
432 if isinstance(self, W_CDataGCP):
433 self.detach_destructor()
434 w_res = space.w_None
435 else:
436 raise oefmt(space.w_TypeError,
437 "Can remove destructor only on a object "
438 "previously returned by ffi.gc()")
439 else:
440 with self as ptr:
441 w_res = W_CDataGCP(space, ptr, self.ctype, self, w_destructor)
442 if size != 0:
443 if isinstance(w_res, W_CDataGCP):
444 rgc.add_memory_pressure(size, w_res)
445 else:
446 rgc.add_memory_pressure(size, self)
447 return w_res
448
449 def unpack(self, length):
450 from pypy.module._cffi_backend.ctypeptr import W_CTypePtrOrArray
451 space = self.space
452 if not self.ctype.is_nonfunc_pointer_or_array:
453 raise oefmt(space.w_TypeError,
454 "expected a pointer or array, got '%s'",
455 self.ctype.name)
456 if length < 0:
457 raise oefmt(space.w_ValueError, "'length' cannot be negative")
458 ctype = self.ctype
459 assert isinstance(ctype, W_CTypePtrOrArray)
460 with self as ptr:
461 if not ptr:
462 raise oefmt(space.w_RuntimeError,
463 "cannot use unpack() on %R",
464 self)
465 w_result = ctype.ctitem.unpack_ptr(ctype, ptr, length)
466 return w_result
467
468 def dir(self, space):
469 from pypy.module._cffi_backend.ctypeptr import W_CTypePointer
470 ct = self.ctype
471 if isinstance(ct, W_CTypePointer):
472 ct = ct.ctitem
473 lst = ct.cdata_dir()
474 return space.newlist([space.newtext(s) for s in lst])
475
476 def get_structobj(self):
477 return None
478
479 def enter_exit(self, exit_now):
480 raise oefmt(self.space.w_ValueError,
481 "only 'cdata' object from ffi.new(), ffi.gc(), ffi.from_buffer() "
482 "or ffi.new_allocator()() can be used with the 'with' keyword or "
483 "ffi.release()")
484
485 def descr_enter(self):
486 self.enter_exit(False)
487 return self
488
489 def descr_exit(self, args_w):
490 self.enter_exit(True)
491
492 def get_maximum_buffer_size(self):
493 return -1
494
495
496 class W_CDataMem(W_CData):
497 """This is used only by the results of cffi.cast('int', x)
498 or other primitive explicitly-casted types."""
499 _attrs_ = []
500
501 def __init__(self, space, ctype):
502 cdata = lltype.malloc(rffi.CCHARP.TO, ctype.size, flavor='raw',
503 zero=False)
504 W_CData.__init__(self, space, cdata, ctype)
505
506 @rgc.must_be_light_finalizer
507 def __del__(self):
508 lltype.free(self._ptr, flavor='raw')
509
510
511 class W_CDataNewOwning(W_CData):
512 """This is the abstract base class used for cdata objects created
513 by newp(). They create and free their own memory according to an
514 allocator."""
515
516 # the 'allocated_length' is >= 0 for arrays; for var-sized
517 # structures it is the total size in bytes; otherwise it is -1.
518 _attrs_ = ['allocated_length']
519 _immutable_fields_ = ['allocated_length']
520
521 def __init__(self, space, cdata, ctype, length=-1):
522 W_CData.__init__(self, space, cdata, ctype)
523 self.allocated_length = length
524
525 def _repr_extra(self):
526 return self._repr_extra_owning()
527
528 def _sizeof(self):
529 ctype = self.ctype
530 if self.allocated_length >= 0:
531 from pypy.module._cffi_backend import ctypearray
532 if isinstance(ctype, ctypearray.W_CTypeArray):
533 return self.allocated_length * ctype.ctitem.size
534 else:
535 return self.allocated_length # var-sized struct size
536 else:
537 return ctype.size
538
539 def get_array_length(self):
540 from pypy.module._cffi_backend import ctypearray
541 assert isinstance(self.ctype, ctypearray.W_CTypeArray)
542 return self.allocated_length
543
544 def get_structobj(self):
545 return self
546
547 def enter_exit(self, exit_now):
548 from pypy.module._cffi_backend.ctypeptr import W_CTypePtrOrArray
549 if not isinstance(self.ctype, W_CTypePtrOrArray):
550 W_CData.enter_exit(self, exit_now)
551 elif exit_now:
552 self._do_exit()
553
554 def _do_exit(self):
555 raise NotImplementedError
556
557
558 class W_CDataNewStd(W_CDataNewOwning):
559 """Subclass using the standard allocator, lltype.malloc()/lltype.free()"""
560 _attrs_ = ['datasize'] # changed to -1 after being explicitly freed
561
562 def __init__(self, space, cdata, ctype, length, datasize):
563 W_CDataNewOwning.__init__(self, space, cdata, ctype, length)
564 assert datasize >= 0
565 self.datasize = datasize
566
567 @rgc.must_be_light_finalizer
568 def __del__(self):
569 if self.datasize >= 0:
570 lltype.free(self._ptr, flavor='raw')
571
572 def _do_exit(self):
573 if self.datasize >= 0:
574 rgc.add_memory_pressure(-self.datasize, self)
575 self.datasize = -1
576 rgc.may_ignore_finalizer(self)
577 lltype.free(self._ptr, flavor='raw')
578
579 def get_maximum_buffer_size(self):
580 return self.datasize
581
582
583 class W_CDataNewNonStd(W_CDataNewOwning):
584 """Subclass using a non-standard allocator"""
585 _attrs_ = ['w_raw_cdata', 'w_free']
586
587 def _finalize_(self):
588 if self.w_free is not None:
589 self.space.call_function(self.w_free, self.w_raw_cdata)
590
591 def _do_exit(self):
592 w_free = self.w_free
593 if w_free is not None:
594 rgc.add_memory_pressure(-self._sizeof(), self)
595 self.w_free = None
596 self.may_unregister_rpython_finalizer(self.space)
597 self.space.call_function(w_free, self.w_raw_cdata)
598
599
600 class W_CDataPtrToStructOrUnion(W_CData):
601 """This subclass is used for the pointer returned by new('struct foo *').
602 It has a strong reference to a W_CDataNewOwning that really owns the
603 struct, which is the object returned by the app-level expression 'p[0]'.
604 But it is not itself owning any memory, although its repr says so;
605 it is merely a co-owner."""
606 _attrs_ = ['structobj']
607 _immutable_fields_ = ['structobj']
608
609 def __init__(self, space, cdata, ctype, structobj):
610 W_CData.__init__(self, space, cdata, ctype)
611 self.structobj = structobj
612
613 def _repr_extra(self):
614 return self.structobj._repr_extra_owning()
615
616 def _do_getitem(self, ctype, i):
617 assert i == 0
618 return self.structobj
619
620 def get_structobj(self):
621 structobj = self.structobj
622 if isinstance(structobj, W_CDataNewOwning):
623 return structobj
624 else:
625 return None
626
627 def enter_exit(self, exit_now):
628 if exit_now:
629 structobj = self.structobj
630 if isinstance(structobj, W_CDataNewOwning):
631 structobj._do_exit()
632
633 def get_maximum_buffer_size(self):
634 return self.structobj._sizeof()
635
636
637 class W_CDataSliced(W_CData):
638 """Subclass with an explicit length, for slices."""
639 _attrs_ = ['length']
640 _immutable_fields_ = ['length']
641
642 def __init__(self, space, cdata, ctype, length):
643 W_CData.__init__(self, space, cdata, ctype)
644 self.length = length
645
646 def _repr_extra(self):
647 return "sliced length %d" % (self.length,)
648
649 def get_array_length(self):
650 return self.length
651
652 def _sizeof(self):
653 from pypy.module._cffi_backend.ctypeptr import W_CTypePtrOrArray
654 ctype = self.ctype
655 assert isinstance(ctype, W_CTypePtrOrArray)
656 return self.length * ctype.ctitem.size
657
658
659 class W_CDataHandle(W_CData):
660 _attrs_ = ['w_keepalive']
661 _immutable_fields_ = ['w_keepalive']
662
663 def __init__(self, space, cdata, ctype, w_keepalive):
664 W_CData.__init__(self, space, cdata, ctype)
665 self.w_keepalive = w_keepalive
666
667 def _repr_extra(self):
668 w_repr = self.space.repr(self.w_keepalive)
669 return "handle to %s" % (self.space.text_w(w_repr),)
670
671
672 class W_CDataFromBuffer(W_CData):
673 _attrs_ = ['buf', 'length', 'w_keepalive']
674 _immutable_fields_ = ['buf', 'length']
675
676 def __init__(self, space, cdata, length, ctype, buf, w_object):
677 W_CData.__init__(self, space, cdata, ctype)
678 self.buf = buf
679 self.length = length
680 self.w_keepalive = w_object
681
682 def get_array_length(self):
683 return self.length
684
685 def _sizeof(self):
686 from pypy.module._cffi_backend import ctypearray
687 ctype = self.ctype
688 if isinstance(ctype, ctypearray.W_CTypeArray):
689 return self.length * ctype.ctitem.size
690 else:
691 return W_CData._sizeof(self)
692
693 def _repr_extra(self):
694 from pypy.module._cffi_backend import ctypearray
695 if self.w_keepalive is None:
696 return "buffer RELEASED"
697 obj_tp_name = self.space.type(self.w_keepalive).name
698 if isinstance(self.ctype, ctypearray.W_CTypeArray):
699 return "buffer len %d from '%s' object" % (self.length, obj_tp_name)
700 else:
701 return "buffer from '%s' object" % (obj_tp_name,)
702
703 def enter_exit(self, exit_now):
704 # for now, limited effect on PyPy
705 if exit_now:
706 self.w_keepalive = None
707
708
709 class W_CDataGCP(W_CData):
710 """For ffi.gc()."""
711 _attrs_ = ['w_original_cdata', 'w_destructor']
712 _immutable_fields_ = ['w_original_cdata']
713
714 def __init__(self, space, cdata, ctype, w_original_cdata, w_destructor):
715 W_CData.__init__(self, space, cdata, ctype)
716 self.w_original_cdata = w_original_cdata
717 self.w_destructor = w_destructor
718 self.register_finalizer(space)
719
720 def _finalize_(self):
721 self.invoke_finalizer()
722
723 def invoke_finalizer(self):
724 w_destructor = self.w_destructor
725 if w_destructor is not None:
726 self.w_destructor = None
727 self.space.call_function(w_destructor, self.w_original_cdata)
728
729 def detach_destructor(self):
730 self.w_destructor = None
731 self.may_unregister_rpython_finalizer(self.space)
732
733 def enter_exit(self, exit_now):
734 if exit_now:
735 self.may_unregister_rpython_finalizer(self.space)
736 self.invoke_finalizer()
737
738
739 W_CData.typedef = TypeDef(
740 '_cffi_backend._CDataBase',
741 __doc__ = "The internal base type for CData objects. Use FFI.CData to "
742 "access it. Always check with isinstance(): subtypes are "
743 "sometimes returned on CPython, for performance reasons.",
744 __module__ = '_cffi_backend', # attribute also visible on instances
745 __name__ = '<cdata>', # attribute also visible on instances
746 __repr__ = interp2app(W_CData.repr),
747 __bool__ = interp2app(W_CData.bool),
748 __int__ = interp2app(W_CData.int),
749 __float__ = interp2app(W_CData.float),
750 __complex__ = interp2app(W_CData.complex),
751 __len__ = interp2app(W_CData.len),
752 __lt__ = interp2app(W_CData.lt),
753 __le__ = interp2app(W_CData.le),
754 __eq__ = interp2app(W_CData.eq),
755 __ne__ = interp2app(W_CData.ne),
756 __gt__ = interp2app(W_CData.gt),
757 __ge__ = interp2app(W_CData.ge),
758 __hash__ = interp2app(W_CData.hash),
759 __getitem__ = interp2app(W_CData.getitem),
760 __setitem__ = interp2app(W_CData.setitem),
761 __add__ = interp2app(W_CData.add),
762 __radd__ = interp2app(W_CData.add),
763 __sub__ = interp2app(W_CData.sub),
764 __getattr__ = interp2app(W_CData.getattr),
765 __setattr__ = interp2app(W_CData.setattr),
766 __call__ = interp2app(W_CData.call),
767 __iter__ = interp2app(W_CData.iter),
768 __weakref__ = make_weakref_descr(W_CData),
769 __dir__ = interp2app(W_CData.dir),
770 __enter__ = interp2app(W_CData.descr_enter),
771 __exit__ = interp2app(W_CData.descr_exit),
772 )
773 W_CData.typedef.acceptable_as_base_class = False