Debian Codegraph @

lib-python/3/ctypes/__init__.py

raw symbols SCIP
1 """create and manipulate C data types in Python"""
2
3 import os as _os, sys as _sys
4 import types as _types
5
6 __version__ = "1.1.0"
7
8 #PyPy change
9 import _ffi
10 from _ctypes import Union, Structure, Array
11 from _ctypes import _Pointer
12 from _ctypes import CFuncPtr as _CFuncPtr
13 from _ctypes import __version__ as _ctypes_version
14 from _ctypes import RTLD_LOCAL, RTLD_GLOBAL
15 from _ctypes import ArgumentError
16
17 from struct import calcsize as _calcsize
18
19 if __version__ != _ctypes_version:
20 raise Exception("Version number mismatch", __version__, _ctypes_version)
21
22 if _os.name == "nt":
23 from _ctypes import FormatError
24
25 DEFAULT_MODE = RTLD_LOCAL
26 if _os.name == "posix" and _sys.platform == "darwin":
27 # On OS X 10.3, we use RTLD_GLOBAL as default mode
28 # because RTLD_LOCAL does not work at least on some
29 # libraries. OS X 10.3 is Darwin 7, so we check for
30 # that.
31
32 if int(_os.uname().release.split('.')[0]) < 8:
33 DEFAULT_MODE = RTLD_GLOBAL
34
35 from _ctypes import FUNCFLAG_CDECL as _FUNCFLAG_CDECL, \
36 FUNCFLAG_PYTHONAPI as _FUNCFLAG_PYTHONAPI, \
37 FUNCFLAG_USE_ERRNO as _FUNCFLAG_USE_ERRNO, \
38 FUNCFLAG_USE_LASTERROR as _FUNCFLAG_USE_LASTERROR
39
40 # WINOLEAPI -> HRESULT
41 # WINOLEAPI_(type)
42 #
43 # STDMETHODCALLTYPE
44 #
45 # STDMETHOD(name)
46 # STDMETHOD_(type, name)
47 #
48 # STDAPICALLTYPE
49
50 def create_string_buffer(init, size=None):
51 """create_string_buffer(aBytes) -> character array
52 create_string_buffer(anInteger) -> character array
53 create_string_buffer(aBytes, anInteger) -> character array
54 """
55 if isinstance(init, bytes):
56 if size is None:
57 size = len(init)+1
58 _sys.audit("ctypes.create_string_buffer", init, size)
59 buftype = c_char * size
60 buf = buftype()
61 buf.value = init
62 return buf
63 elif isinstance(init, int):
64 _sys.audit("ctypes.create_string_buffer", None, init)
65 buftype = c_char * init
66 buf = buftype()
67 return buf
68 raise TypeError(init)
69
70 # Alias to create_string_buffer() for backward compatibility
71 c_buffer = create_string_buffer
72
73 _c_functype_cache = {}
74 def CFUNCTYPE(restype, *argtypes, **kw):
75 """CFUNCTYPE(restype, *argtypes,
76 use_errno=False, use_last_error=False) -> function prototype.
77
78 restype: the result type
79 argtypes: a sequence specifying the argument types
80
81 The function prototype can be called in different ways to create a
82 callable object:
83
84 prototype(integer address) -> foreign function
85 prototype(callable) -> create and return a C callable function from callable
86 prototype(integer index, method name[, paramflags]) -> foreign function calling a COM method
87 prototype((ordinal number, dll object)[, paramflags]) -> foreign function exported by ordinal
88 prototype((function name, dll object)[, paramflags]) -> foreign function exported by name
89 """
90 flags = _FUNCFLAG_CDECL
91 if kw.pop("use_errno", False):
92 flags |= _FUNCFLAG_USE_ERRNO
93 if kw.pop("use_last_error", False):
94 flags |= _FUNCFLAG_USE_LASTERROR
95 if kw:
96 raise ValueError("unexpected keyword argument(s) %s" % kw.keys())
97
98 try:
99 return _c_functype_cache[(restype, argtypes, flags)]
100 except KeyError:
101 pass
102
103 class CFunctionType(_CFuncPtr):
104 _argtypes_ = argtypes
105 _restype_ = restype
106 _flags_ = flags
107 _c_functype_cache[(restype, argtypes, flags)] = CFunctionType
108 return CFunctionType
109
110 if _os.name == "nt":
111 from _ctypes import LoadLibrary as _dlopen
112 from _ctypes import FUNCFLAG_STDCALL as _FUNCFLAG_STDCALL
113
114 _win_functype_cache = {}
115 def WINFUNCTYPE(restype, *argtypes, **kw):
116 # docstring set later (very similar to CFUNCTYPE.__doc__)
117 flags = _FUNCFLAG_STDCALL
118 if kw.pop("use_errno", False):
119 flags |= _FUNCFLAG_USE_ERRNO
120 if kw.pop("use_last_error", False):
121 flags |= _FUNCFLAG_USE_LASTERROR
122 if kw:
123 raise ValueError("unexpected keyword argument(s) %s" % kw.keys())
124
125 try:
126 return _win_functype_cache[(restype, argtypes, flags)]
127 except KeyError:
128 pass
129
130 class WinFunctionType(_CFuncPtr):
131 _argtypes_ = argtypes
132 _restype_ = restype
133 _flags_ = flags
134 _win_functype_cache[(restype, argtypes, flags)] = WinFunctionType
135 return WinFunctionType
136 if WINFUNCTYPE.__doc__:
137 WINFUNCTYPE.__doc__ = CFUNCTYPE.__doc__.replace("CFUNCTYPE", "WINFUNCTYPE")
138
139 elif _os.name == "posix":
140 from _ctypes import dlopen as _dlopen
141
142 from _ctypes import sizeof, byref, addressof, alignment, resize
143 from _ctypes import get_errno, set_errno
144 from _ctypes import _SimpleCData
145
146 def _check_size(typ, typecode=None):
147 # Check if sizeof(ctypes_type) against struct.calcsize. This
148 # should protect somewhat against a misconfigured libffi.
149 from struct import calcsize
150 if typecode is None:
151 # Most _type_ codes are the same as used in struct
152 typecode = typ._type_
153 actual, required = sizeof(typ), calcsize(typecode)
154 if actual != required:
155 raise SystemError("sizeof(%s) wrong: %d instead of %d" % \
156 (typ, actual, required))
157
158 class py_object(_SimpleCData):
159 _type_ = "O"
160 def __repr__(self):
161 try:
162 return super().__repr__()
163 except ValueError:
164 return "%s(<NULL>)" % type(self).__name__
165 _check_size(py_object, "P")
166
167 class c_short(_SimpleCData):
168 _type_ = "h"
169 _check_size(c_short)
170
171 class c_ushort(_SimpleCData):
172 _type_ = "H"
173 _check_size(c_ushort)
174
175 class c_long(_SimpleCData):
176 _type_ = "l"
177 _check_size(c_long)
178
179 class c_ulong(_SimpleCData):
180 _type_ = "L"
181 _check_size(c_ulong)
182
183 if _calcsize("i") == _calcsize("l"):
184 # if int and long have the same size, make c_int an alias for c_long
185 c_int = c_long
186 c_uint = c_ulong
187 else:
188 class c_int(_SimpleCData):
189 _type_ = "i"
190 _check_size(c_int)
191
192 class c_uint(_SimpleCData):
193 _type_ = "I"
194 _check_size(c_uint)
195
196 class c_float(_SimpleCData):
197 _type_ = "f"
198 _check_size(c_float)
199
200 class c_double(_SimpleCData):
201 _type_ = "d"
202 _check_size(c_double)
203
204 class c_longdouble(_SimpleCData):
205 _type_ = "g"
206 if sizeof(c_longdouble) == sizeof(c_double):
207 c_longdouble = c_double
208
209 if _calcsize("l") == _calcsize("q"):
210 # if long and long long have the same size, make c_longlong an alias for c_long
211 c_longlong = c_long
212 c_ulonglong = c_ulong
213 else:
214 class c_longlong(_SimpleCData):
215 _type_ = "q"
216 _check_size(c_longlong)
217
218 class c_ulonglong(_SimpleCData):
219 _type_ = "Q"
220 ## def from_param(cls, val):
221 ## return ('d', float(val), val)
222 ## from_param = classmethod(from_param)
223 _check_size(c_ulonglong)
224
225 class c_ubyte(_SimpleCData):
226 _type_ = "B"
227 c_ubyte.__ctype_le__ = c_ubyte.__ctype_be__ = c_ubyte
228 # backward compatibility:
229 ##c_uchar = c_ubyte
230 _check_size(c_ubyte)
231
232 class c_byte(_SimpleCData):
233 _type_ = "b"
234 c_byte.__ctype_le__ = c_byte.__ctype_be__ = c_byte
235 _check_size(c_byte)
236
237 class c_char(_SimpleCData):
238 _type_ = "c"
239 c_char.__ctype_le__ = c_char.__ctype_be__ = c_char
240 _check_size(c_char)
241
242 class c_char_p(_SimpleCData):
243 _type_ = "z"
244 def __repr__(self):
245 return "%s(%s)" % (self.__class__.__name__, c_void_p.from_buffer(self).value)
246 _check_size(c_char_p, "P")
247
248 class c_void_p(_SimpleCData):
249 _type_ = "P"
250 c_voidp = c_void_p # backwards compatibility (to a bug)
251 _check_size(c_void_p)
252
253 class c_bool(_SimpleCData):
254 _type_ = "?"
255
256 from _ctypes import POINTER, pointer, _pointer_type_cache
257
258 class c_wchar_p(_SimpleCData):
259 _type_ = "Z"
260 def __repr__(self):
261 return "%s(%s)" % (self.__class__.__name__, c_void_p.from_buffer(self).value)
262
263 class c_wchar(_SimpleCData):
264 _type_ = "u"
265
266 def _reset_cache():
267 _pointer_type_cache.clear()
268 _c_functype_cache.clear()
269 if _os.name == "nt":
270 _win_functype_cache.clear()
271 # _SimpleCData.c_wchar_p_from_param
272 POINTER(c_wchar).from_param = c_wchar_p.from_param
273 # _SimpleCData.c_char_p_from_param
274 POINTER(c_char).from_param = c_char_p.from_param
275 _pointer_type_cache[None] = c_void_p
276
277 def create_unicode_buffer(init, size=None):
278 """create_unicode_buffer(aString) -> character array
279 create_unicode_buffer(anInteger) -> character array
280 create_unicode_buffer(aString, anInteger) -> character array
281 """
282 if isinstance(init, str):
283 if size is None:
284 if sizeof(c_wchar) == 2:
285 # UTF-16 requires a surrogate pair (2 wchar_t) for non-BMP
286 # characters (outside [U+0000; U+FFFF] range). +1 for trailing
287 # NUL character.
288 size = sum(2 if ord(c) > 0xFFFF else 1 for c in init) + 1
289 else:
290 # 32-bit wchar_t (1 wchar_t per Unicode character). +1 for
291 # trailing NUL character.
292 size = len(init) + 1
293 _sys.audit("ctypes.create_unicode_buffer", init, size)
294 buftype = c_wchar * size
295 buf = buftype()
296 buf.value = init
297 return buf
298 elif isinstance(init, int):
299 _sys.audit("ctypes.create_unicode_buffer", None, init)
300 buftype = c_wchar * init
301 buf = buftype()
302 return buf
303 raise TypeError(init)
304
305
306 # XXX Deprecated
307 def SetPointerType(pointer, cls):
308 if _pointer_type_cache.get(cls, None) is not None:
309 raise RuntimeError("This type already exists in the cache")
310 if id(pointer) not in _pointer_type_cache:
311 raise RuntimeError("What's this???")
312 pointer.set_type(cls)
313 _pointer_type_cache[cls] = pointer
314 del _pointer_type_cache[id(pointer)]
315
316 # XXX Deprecated
317 def ARRAY(typ, len):
318 return typ * len
319
320 ################################################################
321
322
323 class CDLL(object):
324 """An instance of this class represents a loaded dll/shared
325 library, exporting functions using the standard C calling
326 convention (named 'cdecl' on Windows).
327
328 The exported functions can be accessed as attributes, or by
329 indexing with the function name. Examples:
330
331 <obj>.qsort -> callable object
332 <obj>['qsort'] -> callable object
333
334 Calling the functions releases the Python GIL during the call and
335 reacquires it afterwards.
336 """
337 _func_flags_ = _FUNCFLAG_CDECL
338 _func_restype_ = c_int
339 # default values for repr
340 _name = '<uninitialized>'
341 _handle = 0
342 _FuncPtr = None
343
344 def __init__(self, name, mode=DEFAULT_MODE, handle=None,
345 use_errno=False,
346 use_last_error=False,
347 winmode=None):
348 self._name = name
349 flags = self._func_flags_
350 if use_errno:
351 flags |= _FUNCFLAG_USE_ERRNO
352 if use_last_error:
353 flags |= _FUNCFLAG_USE_LASTERROR
354 if _sys.platform.startswith("aix"):
355 """When the name contains ".a(" and ends with ")",
356 e.g., "libFOO.a(libFOO.so)" - this is taken to be an
357 archive(member) syntax for dlopen(), and the mode is adjusted.
358 Otherwise, name is presented to dlopen() as a file argument.
359 """
360 if name and name.endswith(")") and ".a(" in name:
361 mode |= ( _os.RTLD_MEMBER | _os.RTLD_NOW )
362 if _os.name == "nt":
363 if winmode is not None:
364 mode = winmode
365 else:
366 import nt
367 mode = nt._LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
368 if '/' in name or '\\' in name:
369 self._name = nt._getfullpathname(self._name)
370 mode |= nt._LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
371
372 class _FuncPtr(_CFuncPtr):
373 _flags_ = flags
374 _restype_ = self._func_restype_
375 self._FuncPtr = _FuncPtr
376
377 if handle is None:
378 # PyPy change
379 if flags & _FUNCFLAG_CDECL:
380 pypy_dll = _ffi.CDLL(name, mode)
381 else:
382 pypy_dll = _ffi.WinDLL(name, mode)
383 self._handle = pypy_dll
384 else:
385 self._handle = handle
386
387 def __repr__(self):
388 return "<%s '%s', handle %x at %#x>" % \
389 (self.__class__.__name__, self._name,
390 (self._handle & (_sys.maxsize*2 + 1)),
391 id(self) & (_sys.maxsize*2 + 1))
392
393 def __getattr__(self, name):
394 if name.startswith('__') and name.endswith('__'):
395 raise AttributeError(name)
396 func = self.__getitem__(name)
397 setattr(self, name, func)
398 return func
399
400 def __getitem__(self, name_or_ordinal):
401 func = self._FuncPtr((name_or_ordinal, self))
402 if not isinstance(name_or_ordinal, int):
403 func.__name__ = name_or_ordinal
404 return func
405
406 # Not in PyPy
407 #class PyDLL(CDLL):
408 # """This class represents the Python library itself. It allows
409 # accessing Python API functions. The GIL is not released, and
410 # Python exceptions are handled correctly.
411 # """
412 # _func_flags_ = _FUNCFLAG_CDECL | _FUNCFLAG_PYTHONAPI
413
414 if _os.name == "nt":
415
416 class WinDLL(CDLL):
417 """This class represents a dll exporting functions using the
418 Windows stdcall calling convention.
419 """
420 _func_flags_ = _FUNCFLAG_STDCALL
421
422 # XXX Hm, what about HRESULT as normal parameter?
423 # Mustn't it derive from c_long then?
424 from _ctypes import _check_HRESULT, _SimpleCData
425 class HRESULT(_SimpleCData):
426 _type_ = "l"
427 # _check_retval_ is called with the function's result when it
428 # is used as restype. It checks for the FAILED bit, and
429 # raises an OSError if it is set.
430 #
431 # The _check_retval_ method is implemented in C, so that the
432 # method definition itself is not included in the traceback
433 # when it raises an error - that is what we want (and Python
434 # doesn't have a way to raise an exception in the caller's
435 # frame).
436 _check_retval_ = _check_HRESULT
437
438 class OleDLL(CDLL):
439 """This class represents a dll exporting functions using the
440 Windows stdcall calling convention, and returning HRESULT.
441 HRESULT error values are automatically raised as OSError
442 exceptions.
443 """
444 _func_flags_ = _FUNCFLAG_STDCALL
445 _func_restype_ = HRESULT
446
447 class LibraryLoader(object):
448 def __init__(self, dlltype):
449 self._dlltype = dlltype
450
451 def __getattr__(self, name):
452 if name[0] == '_':
453 raise AttributeError(name)
454 dll = self._dlltype(name)
455 setattr(self, name, dll)
456 return dll
457
458 def __getitem__(self, name):
459 return getattr(self, name)
460
461 def LoadLibrary(self, name):
462 return self._dlltype(name)
463
464 __class_getitem__ = classmethod(_types.GenericAlias)
465
466 cdll = LibraryLoader(CDLL)
467 # not on PyPy
468 #pydll = LibraryLoader(PyDLL)
469
470 if _os.name == "nt":
471 windll = LibraryLoader(WinDLL)
472 oledll = LibraryLoader(OleDLL)
473
474 GetLastError = windll.kernel32.GetLastError
475 from _ctypes import get_last_error, set_last_error
476
477 def WinError(code=None, descr=None):
478 if code is None:
479 code = GetLastError()
480 if descr is None:
481 descr = FormatError(code).strip()
482 return OSError(None, descr, None, code)
483
484 if sizeof(c_uint) == sizeof(c_void_p):
485 c_size_t = c_uint
486 c_ssize_t = c_int
487 elif sizeof(c_ulong) == sizeof(c_void_p):
488 c_size_t = c_ulong
489 c_ssize_t = c_long
490 elif sizeof(c_ulonglong) == sizeof(c_void_p):
491 c_size_t = c_ulonglong
492 c_ssize_t = c_longlong
493
494 # functions
495
496 from _ctypes import _memmove_addr, _memset_addr, _string_at_addr, _cast_addr
497
498 ## void *memmove(void *, const void *, size_t);
499 memmove = CFUNCTYPE(c_void_p, c_void_p, c_void_p, c_size_t)(_memmove_addr)
500
501 ## void *memset(void *, int, size_t)
502 memset = CFUNCTYPE(c_void_p, c_void_p, c_int, c_size_t)(_memset_addr)
503
504 def PYFUNCTYPE(restype, *argtypes):
505 class CFunctionType(_CFuncPtr):
506 _argtypes_ = argtypes
507 _restype_ = restype
508 _flags_ = _FUNCFLAG_CDECL | _FUNCFLAG_PYTHONAPI
509 return CFunctionType
510
511 def cast(obj, typ):
512 # PyPy difference: call _cast_addr directly, don't wrap it in a PYFUNCTYPE
513 try:
514 c_void_p.from_param(obj)
515 except TypeError as e:
516 raise ArgumentError(str(e))
517 return _cast_addr(obj, obj, typ)
518
519 _string_at = PYFUNCTYPE(py_object, c_void_p, c_int)(_string_at_addr)
520 def string_at(ptr, size=-1):
521 """string_at(addr[, size]) -> string
522
523 Return the string at addr."""
524 return _string_at(ptr, size)
525
526 try:
527 from _ctypes import _wstring_at_addr
528 except ImportError:
529 pass
530 else:
531 _wstring_at = PYFUNCTYPE(py_object, c_void_p, c_int)(_wstring_at_addr)
532 def wstring_at(ptr, size=-1):
533 """wstring_at(addr[, size]) -> string
534
535 Return the string at addr."""
536 return _wstring_at(ptr, size)
537
538
539 if _os.name == "nt": # COM stuff
540 def DllGetClassObject(rclsid, riid, ppv):
541 try:
542 ccom = __import__("comtypes.server.inprocserver", globals(), locals(), ['*'])
543 except ImportError:
544 return -2147221231 # CLASS_E_CLASSNOTAVAILABLE
545 else:
546 return ccom.DllGetClassObject(rclsid, riid, ppv)
547
548 def DllCanUnloadNow():
549 try:
550 ccom = __import__("comtypes.server.inprocserver", globals(), locals(), ['*'])
551 except ImportError:
552 return 0 # S_OK
553 return ccom.DllCanUnloadNow()
554
555 from ctypes._endian import BigEndianStructure, LittleEndianStructure
556 from ctypes._endian import BigEndianUnion, LittleEndianUnion
557
558 # Fill in specifically-sized types
559 c_int8 = c_byte
560 c_uint8 = c_ubyte
561 for kind in [c_short, c_int, c_long, c_longlong]:
562 if sizeof(kind) == 2: c_int16 = kind
563 elif sizeof(kind) == 4: c_int32 = kind
564 elif sizeof(kind) == 8: c_int64 = kind
565 for kind in [c_ushort, c_uint, c_ulong, c_ulonglong]:
566 if sizeof(kind) == 2: c_uint16 = kind
567 elif sizeof(kind) == 4: c_uint32 = kind
568 elif sizeof(kind) == 8: c_uint64 = kind
569 del(kind)
570
571 _reset_cache()