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