Debian Codegraph @

lib_pypy/_ctypes/basics.py

raw symbols SCIP
1 import _rawffi
2 from _rawffi import alt as _ffi
3 from __pypy__ import newmemoryview
4 import sys
5
6 try:
7 from __pypy__ import builtinify
8 except ImportError:
9 builtinify = lambda f: f
10
11 try:
12 from __pypy__.bufferable import bufferable
13 except ImportError:
14 bufferable = object
15
16 keepalive_key = str # XXX fix this when provided with test
17
18 def ensure_objects(where):
19 try:
20 ensure = where._ensure_objects
21 except AttributeError:
22 return None
23 return ensure()
24
25 def store_reference(where, base_key, target):
26 if '_index' not in where.__dict__:
27 # shortcut
28 where._ensure_objects()[str(base_key)] = target
29 return
30 key = [base_key]
31 while '_index' in where.__dict__:
32 key.append(where.__dict__['_index'])
33 where = where.__dict__['_base']
34 real_key = ":".join([str(i) for i in key])
35 where._ensure_objects()[real_key] = target
36
37 class ArgumentError(Exception):
38 pass
39
40 class _ctypes_property(property):
41 """A property subclass that raises TypeError (not AttributeError) on delete,
42 matching CPython ctypes behaviour."""
43 def __delete__(self, obj):
44 raise TypeError("cannot delete attribute")
45
46 class COMError(Exception):
47 "Raised when a COM method call failed."
48 def __init__(self, hresult, text, details):
49 self.args = (hresult, text, details)
50 self.hresult = hresult
51 self.text = text
52 self.details = details
53
54 class _CDataMeta(type):
55 def _is_abstract(self):
56 return getattr(self, '_type_', 'abstract') == 'abstract'
57
58 def from_param(self, value):
59 if isinstance(value, self):
60 return value
61 try:
62 as_parameter = value._as_parameter_
63 except AttributeError:
64 raise TypeError("expected %s instance instead of %s" % (
65 self.__name__, type(value).__name__))
66 else:
67 return self.from_param(as_parameter)
68
69 def _build_ffiargtype(self):
70 return _shape_to_ffi_type(self._ffiargshape_)
71
72 def get_ffi_argtype(self):
73 if self._ffiargtype:
74 return self._ffiargtype
75 self._ffiargtype = self._build_ffiargtype()
76 return self._ffiargtype
77
78 def _CData_output(self, resbuffer, base=None, index=-1):
79 #assert isinstance(resbuffer, _rawffi.ArrayInstance)
80 """Used when data exits ctypes and goes into user code.
81 'resbuffer' is a _rawffi array of length 1 containing the value,
82 and this returns a general Python object that corresponds.
83 """
84 res = bufferable.__new__(self)
85 res.__class__ = self
86 res.__dict__['_buffer'] = resbuffer
87 if base is not None:
88 res.__dict__['_base'] = base
89 res.__dict__['_index'] = index
90 return res
91
92 def _CData_retval(self, resbuffer):
93 return self._CData_output(resbuffer)
94
95 def __mul__(self, other):
96 from _ctypes.array import create_array_type
97 return create_array_type(self, other)
98
99 __rmul__ = __mul__
100
101 def _is_pointer_like(self):
102 return False
103
104 def _has_pointer(self):
105 return False
106
107 def in_dll(self, dll, name):
108 return self.from_address(dll._handle.getaddressindll(name))
109
110 def from_buffer(self, obj, offset=0):
111 if self._is_abstract():
112 raise TypeError('abstract class')
113 if offset < 0:
114 raise ValueError("offset cannot be negative")
115 size = self._sizeofinstances()
116 buf = memoryview(obj)
117 if buf.nbytes < offset + size:
118 raise ValueError(
119 "Buffer size too small (%d instead of at least %d bytes)"
120 % (buf.nbytes, offset + size))
121 raw_addr = buf._pypy_raw_address() + offset
122 result = self.from_address(raw_addr)
123 objects = result._ensure_objects()
124 if objects is not None:
125 objects['ffffffff'] = obj
126 else: # case e.g. of a primitive type like c_int
127 result._objects = obj
128 return result
129
130 def from_buffer_copy(self, obj, offset=0):
131 if self._is_abstract():
132 raise TypeError('abstract class')
133 if offset < 0:
134 raise ValueError("offset cannot be negative")
135 size = self._sizeofinstances()
136 buf = memoryview(obj)
137 if buf.nbytes < offset + size:
138 raise ValueError(
139 "Buffer size too small (%d instead of at least %d bytes)"
140 % (buf.nbytes, offset + size))
141 result = self._newowninstance_()
142 dest = result._buffer.buffer
143 try:
144 raw_addr = buf._pypy_raw_address() + offset
145 except ValueError:
146 _rawffi.rawstring2charp(dest, buf, offset, size)
147 else:
148 from ctypes import memmove
149 memmove(dest, raw_addr, size)
150 return result
151
152 def _newowninstance_(self):
153 result = self.__new__(self)
154 result._init_no_arg_()
155 return result
156
157 def _getformat(self):
158 raise ValueError('cannot get format string for %r' % self)
159
160
161 class CArgObject(object):
162 """ simple wrapper around buffer, just for the case of freeing
163 it afterwards
164 """
165 def __init__(self, obj, buffer):
166 self._obj = obj
167 self._buffer = buffer
168
169 def __del__(self):
170 self._buffer.free()
171 self._buffer = None
172
173 def __repr__(self):
174 return repr(self._obj)
175
176 def __eq__(self, other):
177 return self._obj == other
178
179 def __ne__(self, other):
180 return self._obj != other
181
182 class _CData(bufferable, metaclass=_CDataMeta):
183 """ The most basic object for all ctypes types
184 """
185 _objects = None
186 _ffiargtype = None
187
188 def __init__(self, *args, **kwds):
189 raise TypeError("%s has no type" % (type(self),))
190 _init_no_arg_ = __init__
191
192 def _ensure_objects(self):
193 if '_objects' not in self.__dict__:
194 if '_index' in self.__dict__:
195 return None
196 self.__dict__['_objects'] = {}
197 return self._objects
198
199 def __ctypes_from_outparam__(self):
200 return self
201
202 def _get_buffer_for_param(self):
203 return self
204
205 def _get_buffer_value(self):
206 return self._buffer[0]
207
208 def _copy_to(self, addr):
209 target = type(self).from_address(addr)._buffer
210 target[0] = self._get_buffer_value()
211
212 def _to_ffi_param(self):
213 if self.__class__._is_pointer_like():
214 return self._get_buffer_value()
215 else:
216 return self.value
217
218 def __buffer__(self, flags):
219 rawview = memoryview(self._buffer)
220 fmt = type(self)._getformat()
221 itemsize = sizeof(type(self))
222 return newmemoryview(rawview, itemsize, fmt, ())
223
224 def _get_b_base(self):
225 try:
226 return self._base
227 except AttributeError:
228 return None
229 _b_base_ = property(_get_b_base)
230 _b_needsfree_ = False
231
232 def __reduce__(self):
233 if type(self)._is_pointer_like() or type(self)._has_pointer():
234 raise ValueError("ctypes objects containing pointers cannot be pickled")
235 d = dict(self.__dict__)
236 del d['_buffer']
237 return (_unpickle, (type(self), (d, bytes(self))))
238
239 @builtinify
240 def _unpickle(cls, tup):
241 dct, buf = tup
242 res = cls.from_buffer_copy(buf)
243 res.__dict__.update(dct)
244 return res
245
246 @builtinify
247 def sizeof(tp):
248 if not isinstance(tp, _CDataMeta):
249 if isinstance(tp, _CData):
250 tp = type(tp)
251 else:
252 raise TypeError("ctypes type or instance expected, got %r" % (
253 type(tp).__name__,))
254 return tp._sizeofinstances()
255
256 @builtinify
257 def alignment(tp):
258 if not isinstance(tp, _CDataMeta):
259 if isinstance(tp, _CData):
260 tp = type(tp)
261 else:
262 raise TypeError("ctypes type or instance expected, got %r" % (
263 type(tp).__name__,))
264 return tp._alignmentofinstances()
265
266 @builtinify
267 def byref(cdata, offset=0):
268 from _ctypes.pointer import pointer
269 ptr = pointer(cdata)
270 if offset != 0:
271 ptr._buffer[0] += offset
272 return ptr
273
274 def cdata_from_address(self, address):
275 # fix the address: turn it into as unsigned, in case it's a negative number
276 address = address & (sys.maxsize * 2 + 1)
277 instance = self.__new__(self)
278 lgt = getattr(self, '_length_', 1)
279 instance._buffer = self._ffiarray.fromaddress(address, lgt)
280 return instance
281
282 @builtinify
283 def addressof(tp):
284 return tp._buffer.buffer
285
286
287 # ----------------------------------------------------------------------
288
289 def is_struct_shape(shape):
290 # see the corresponding code to set the shape in
291 # _ctypes.structure._set_shape
292 return (isinstance(shape, tuple) and
293 len(shape) == 2 and
294 isinstance(shape[0], _rawffi.Structure) and
295 shape[1] == 1)
296
297 # Adding proper longdouble support would require:
298 # 1. rpython/rlib/libffi.py — add types.longdouble =
299 # clibffi.ffi_type_longdouble in _import(), and add elif ffi_type is
300 # types.longdouble: return 'L' in getkind(). getkind() needs a new kind.
301 # 2. rpython/rlib/libffi.py (rest of file) — all dispatch on getkind() result
302 # would need an 'L' case. Likely just a handful of places where 'f'/'s' are
303 # handled.
304 # 3. pypy/module/_rawffi/alt/interp_ffitype.py — add W_FFIType('longdouble',
305 # libffi.types.longdouble) to the types list, and add is_longdouble() method.
306 # 4. pypy/module/_rawffi/alt/type_converter.py — add an elif
307 # w_ffitype.is_longdouble(): self._longdouble(...) branch, plus
308 # handle_longdouble() abstract method and concrete implementations.
309 # 5. lib_pypy/_ctypes/basics.py — add 'g': _ffi.types.longdouble to the typemap.
310
311
312 def _shape_to_ffi_type(shape):
313 try:
314 return _shape_to_ffi_type.typemap[shape]
315 except KeyError:
316 pass
317 if is_struct_shape(shape):
318 return shape[0].get_ffi_type()
319 if shape == 'g': # c_longdouble exists but FFI calls are not yet implemented
320 raise NotImplementedError(
321 "c_longdouble is not supported as a ctypes FFI argument or return type in PyPy")
322 assert False, 'unknown shape %s' % (shape,)
323
324
325 _shape_to_ffi_type.typemap = {
326 'c' : _ffi.types.char,
327 'b' : _ffi.types.sbyte,
328 'B' : _ffi.types.ubyte,
329 'h' : _ffi.types.sshort,
330 'u' : _ffi.types.unichar,
331 'H' : _ffi.types.ushort,
332 'i' : _ffi.types.sint,
333 'I' : _ffi.types.uint,
334 'l' : _ffi.types.slong,
335 'L' : _ffi.types.ulong,
336 'q' : _ffi.types.slonglong,
337 'Q' : _ffi.types.ulonglong,
338 'f' : _ffi.types.float,
339 'd' : _ffi.types.double,
340 's' : _ffi.types.void_p,
341 'P' : _ffi.types.void_p,
342 'z' : _ffi.types.void_p,
343 'O' : _ffi.types.void_p,
344 'Z' : _ffi.types.void_p,
345 'X' : _ffi.types.void_p,
346 'v' : _ffi.types.sshort,
347 '?' : _ffi.types.ubyte,
348 }
349
350
351 # called from primitive.py, pointer.py, array.py
352 def as_ffi_pointer(value, ffitype):
353 my_ffitype = type(value).get_ffi_argtype()
354 # for now, we always allow types.pointer, else a lot of tests
355 # break. We need to rethink how pointers are represented, though
356 if my_ffitype is not ffitype and ffitype is not _ffi.types.void_p:
357 raise ArgumentError("expected %s instance, got %s" % (type(value),
358 ffitype))
359 return value._get_buffer_value()