blob: 1283f28a6d0e22b88fdfa21e1ea80de3b5623d84 [file] [log] [blame]
Thomas Hellerbabddfc2006-03-08 19:56:54 +00001"""create and manipulate C data types in Python"""
2
Thomas Hellerbabddfc2006-03-08 19:56:54 +00003import os as _os, sys as _sys
Thomas Hellerbabddfc2006-03-08 19:56:54 +00004
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +00005__version__ = "1.1.0"
Thomas Hellerbabddfc2006-03-08 19:56:54 +00006
7from _ctypes import Union, Structure, Array
8from _ctypes import _Pointer
9from _ctypes import CFuncPtr as _CFuncPtr
10from _ctypes import __version__ as _ctypes_version
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011from _ctypes import RTLD_LOCAL, RTLD_GLOBAL
Thomas Hellerbabddfc2006-03-08 19:56:54 +000012from _ctypes import ArgumentError
13
14from struct import calcsize as _calcsize
15
16if __version__ != _ctypes_version:
Collin Wintera73bfee2007-08-30 03:47:13 +000017 raise Exception("Version number mismatch", __version__, _ctypes_version)
Thomas Hellerbabddfc2006-03-08 19:56:54 +000018
19if _os.name in ("nt", "ce"):
20 from _ctypes import FormatError
21
Thomas Wouters0e3f5912006-08-11 14:57:12 +000022DEFAULT_MODE = RTLD_LOCAL
23if _os.name == "posix" and _sys.platform == "darwin":
Thomas Wouters0e3f5912006-08-11 14:57:12 +000024 # On OS X 10.3, we use RTLD_GLOBAL as default mode
25 # because RTLD_LOCAL does not work at least on some
Guido van Rossum8ce8a782007-11-01 19:42:39 +000026 # libraries. OS X 10.3 is Darwin 7, so we check for
27 # that.
Thomas Wouters0e3f5912006-08-11 14:57:12 +000028
Guido van Rossum8ce8a782007-11-01 19:42:39 +000029 if int(_os.uname()[2].split('.')[0]) < 8:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000030 DEFAULT_MODE = RTLD_GLOBAL
31
Thomas Hellerbabddfc2006-03-08 19:56:54 +000032from _ctypes import FUNCFLAG_CDECL as _FUNCFLAG_CDECL, \
Thomas Heller9cac7b62008-06-06 09:31:40 +000033 FUNCFLAG_PYTHONAPI as _FUNCFLAG_PYTHONAPI, \
34 FUNCFLAG_USE_ERRNO as _FUNCFLAG_USE_ERRNO, \
35 FUNCFLAG_USE_LASTERROR as _FUNCFLAG_USE_LASTERROR
Thomas Hellerbabddfc2006-03-08 19:56:54 +000036
Thomas Hellerbabddfc2006-03-08 19:56:54 +000037"""
38WINOLEAPI -> HRESULT
39WINOLEAPI_(type)
40
41STDMETHODCALLTYPE
42
43STDMETHOD(name)
44STDMETHOD_(type, name)
45
46STDAPICALLTYPE
47"""
48
49def create_string_buffer(init, size=None):
Guido van Rossum97f9d4f2007-10-24 18:41:19 +000050 """create_string_buffer(aBytes) -> character array
Thomas Hellerbabddfc2006-03-08 19:56:54 +000051 create_string_buffer(anInteger) -> character array
52 create_string_buffer(aString, anInteger) -> character array
53 """
Guido van Rossum97f9d4f2007-10-24 18:41:19 +000054 if isinstance(init, (str, bytes)):
Thomas Hellerbabddfc2006-03-08 19:56:54 +000055 if size is None:
56 size = len(init)+1
57 buftype = c_char * size
58 buf = buftype()
59 buf.value = init
60 return buf
Walter Dörwaldaa97f042007-05-03 21:05:51 +000061 elif isinstance(init, int):
Thomas Hellerbabddfc2006-03-08 19:56:54 +000062 buftype = c_char * init
63 buf = buftype()
64 return buf
Collin Wintera73bfee2007-08-30 03:47:13 +000065 raise TypeError(init)
Thomas Hellerbabddfc2006-03-08 19:56:54 +000066
67def c_buffer(init, size=None):
68## "deprecated, use create_string_buffer instead"
69## import warnings
70## warnings.warn("c_buffer is deprecated, use create_string_buffer instead",
71## DeprecationWarning, stacklevel=2)
72 return create_string_buffer(init, size)
73
74_c_functype_cache = {}
Thomas Heller9cac7b62008-06-06 09:31:40 +000075def CFUNCTYPE(restype, *argtypes, **kw):
76 """CFUNCTYPE(restype, *argtypes,
77 use_errno=False, use_last_error=False) -> function prototype.
Tim Peterse8d09e52006-03-09 01:15:05 +000078
Thomas Hellerbabddfc2006-03-08 19:56:54 +000079 restype: the result type
80 argtypes: a sequence specifying the argument types
Tim Peterse8d09e52006-03-09 01:15:05 +000081
Thomas Wouters0e3f5912006-08-11 14:57:12 +000082 The function prototype can be called in different ways to create a
Thomas Hellerbabddfc2006-03-08 19:56:54 +000083 callable object:
Tim Peterse8d09e52006-03-09 01:15:05 +000084
Thomas Wouters477c8d52006-05-27 19:21:47 +000085 prototype(integer address) -> foreign function
86 prototype(callable) -> create and return a C callable function from callable
87 prototype(integer index, method name[, paramflags]) -> foreign function calling a COM method
88 prototype((ordinal number, dll object)[, paramflags]) -> foreign function exported by ordinal
89 prototype((function name, dll object)[, paramflags]) -> foreign function exported by name
Thomas Hellerbabddfc2006-03-08 19:56:54 +000090 """
Thomas Heller9cac7b62008-06-06 09:31:40 +000091 flags = _FUNCFLAG_CDECL
92 if kw.pop("use_errno", False):
93 flags |= _FUNCFLAG_USE_ERRNO
94 if kw.pop("use_last_error", False):
95 flags |= _FUNCFLAG_USE_LASTERROR
96 if kw:
97 raise ValueError("unexpected keyword argument(s) %s" % kw.keys())
Thomas Hellerbabddfc2006-03-08 19:56:54 +000098 try:
Thomas Heller9cac7b62008-06-06 09:31:40 +000099 return _c_functype_cache[(restype, argtypes, flags)]
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000100 except KeyError:
101 class CFunctionType(_CFuncPtr):
102 _argtypes_ = argtypes
103 _restype_ = restype
Thomas Heller9cac7b62008-06-06 09:31:40 +0000104 _flags_ = flags
105 _c_functype_cache[(restype, argtypes, flags)] = CFunctionType
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000106 return CFunctionType
107
108if _os.name in ("nt", "ce"):
109 from _ctypes import LoadLibrary as _dlopen
110 from _ctypes import FUNCFLAG_STDCALL as _FUNCFLAG_STDCALL
111 if _os.name == "ce":
112 # 'ce' doesn't have the stdcall calling convention
113 _FUNCFLAG_STDCALL = _FUNCFLAG_CDECL
114
115 _win_functype_cache = {}
Thomas Heller9cac7b62008-06-06 09:31:40 +0000116 def WINFUNCTYPE(restype, *argtypes, **kw):
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000117 # docstring set later (very similar to CFUNCTYPE.__doc__)
Thomas Heller9cac7b62008-06-06 09:31:40 +0000118 flags = _FUNCFLAG_STDCALL
119 if kw.pop("use_errno", False):
120 flags |= _FUNCFLAG_USE_ERRNO
121 if kw.pop("use_last_error", False):
122 flags |= _FUNCFLAG_USE_LASTERROR
123 if kw:
124 raise ValueError("unexpected keyword argument(s) %s" % kw.keys())
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000125 try:
Thomas Heller9cac7b62008-06-06 09:31:40 +0000126 return _win_functype_cache[(restype, argtypes, flags)]
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000127 except KeyError:
128 class WinFunctionType(_CFuncPtr):
129 _argtypes_ = argtypes
130 _restype_ = restype
Thomas Heller9cac7b62008-06-06 09:31:40 +0000131 _flags_ = flags
132 _win_functype_cache[(restype, argtypes, flags)] = WinFunctionType
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000133 return WinFunctionType
134 if WINFUNCTYPE.__doc__:
135 WINFUNCTYPE.__doc__ = CFUNCTYPE.__doc__.replace("CFUNCTYPE", "WINFUNCTYPE")
136
137elif _os.name == "posix":
138 from _ctypes import dlopen as _dlopen
139
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000140from _ctypes import sizeof, byref, addressof, alignment, resize
Thomas Heller9cac7b62008-06-06 09:31:40 +0000141from _ctypes import get_errno, set_errno
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000142from _ctypes import _SimpleCData
143
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000144def _check_size(typ, typecode=None):
145 # Check if sizeof(ctypes_type) against struct.calcsize. This
146 # should protect somewhat against a misconfigured libffi.
147 from struct import calcsize
148 if typecode is None:
149 # Most _type_ codes are the same as used in struct
150 typecode = typ._type_
151 actual, required = sizeof(typ), calcsize(typecode)
152 if actual != required:
153 raise SystemError("sizeof(%s) wrong: %d instead of %d" % \
154 (typ, actual, required))
155
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000156class py_object(_SimpleCData):
157 _type_ = "O"
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000158 def __repr__(self):
159 try:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000160 return super().__repr__()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000161 except ValueError:
162 return "%s(<NULL>)" % type(self).__name__
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000163_check_size(py_object, "P")
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000164
165class c_short(_SimpleCData):
166 _type_ = "h"
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000167_check_size(c_short)
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000168
169class c_ushort(_SimpleCData):
170 _type_ = "H"
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000171_check_size(c_ushort)
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000172
173class c_long(_SimpleCData):
174 _type_ = "l"
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000175_check_size(c_long)
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000176
177class c_ulong(_SimpleCData):
178 _type_ = "L"
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000179_check_size(c_ulong)
Tim Peterse8d09e52006-03-09 01:15:05 +0000180
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000181if _calcsize("i") == _calcsize("l"):
182 # if int and long have the same size, make c_int an alias for c_long
183 c_int = c_long
184 c_uint = c_ulong
185else:
186 class c_int(_SimpleCData):
187 _type_ = "i"
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000188 _check_size(c_int)
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000189
190 class c_uint(_SimpleCData):
191 _type_ = "I"
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000192 _check_size(c_uint)
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000193
194class c_float(_SimpleCData):
195 _type_ = "f"
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000196_check_size(c_float)
Tim Peterse8d09e52006-03-09 01:15:05 +0000197
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000198class c_double(_SimpleCData):
199 _type_ = "d"
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000200_check_size(c_double)
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000201
Thomas Wouters89d996e2007-09-08 17:39:28 +0000202class c_longdouble(_SimpleCData):
Thomas Hellerff721222008-01-17 18:46:55 +0000203 _type_ = "g"
Thomas Wouters89d996e2007-09-08 17:39:28 +0000204if sizeof(c_longdouble) == sizeof(c_double):
205 c_longdouble = c_double
206
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000207if _calcsize("l") == _calcsize("q"):
208 # if long and long long have the same size, make c_longlong an alias for c_long
209 c_longlong = c_long
210 c_ulonglong = c_ulong
211else:
212 class c_longlong(_SimpleCData):
213 _type_ = "q"
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000214 _check_size(c_longlong)
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000215
216 class c_ulonglong(_SimpleCData):
217 _type_ = "Q"
218 ## def from_param(cls, val):
219 ## return ('d', float(val), val)
220 ## from_param = classmethod(from_param)
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000221 _check_size(c_ulonglong)
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000222
223class c_ubyte(_SimpleCData):
224 _type_ = "B"
225c_ubyte.__ctype_le__ = c_ubyte.__ctype_be__ = c_ubyte
226# backward compatibility:
227##c_uchar = c_ubyte
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000228_check_size(c_ubyte)
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000229
230class c_byte(_SimpleCData):
231 _type_ = "b"
232c_byte.__ctype_le__ = c_byte.__ctype_be__ = c_byte
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000233_check_size(c_byte)
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000234
235class c_char(_SimpleCData):
236 _type_ = "c"
237c_char.__ctype_le__ = c_char.__ctype_be__ = c_char
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000238_check_size(c_char)
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000239
240class c_char_p(_SimpleCData):
241 _type_ = "z"
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000242 if _os.name == "nt":
243 def __repr__(self):
244 if not windll.kernel32.IsBadStringPtrA(self, -1):
245 return "%s(%r)" % (self.__class__.__name__, self.value)
246 return "%s(%s)" % (self.__class__.__name__, cast(self, c_void_p).value)
247 else:
248 def __repr__(self):
249 return "%s(%s)" % (self.__class__.__name__, cast(self, c_void_p).value)
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000250_check_size(c_char_p, "P")
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000251
252class c_void_p(_SimpleCData):
253 _type_ = "P"
254c_voidp = c_void_p # backwards compatibility (to a bug)
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000255_check_size(c_void_p)
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000256
Guido van Rossumd8faa362007-04-27 19:54:29 +0000257class c_bool(_SimpleCData):
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000258 _type_ = "?"
Guido van Rossumd8faa362007-04-27 19:54:29 +0000259
Thomas Heller3071f812008-04-14 16:17:33 +0000260from _ctypes import POINTER, pointer, _pointer_type_cache
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000261
262try:
263 from _ctypes import set_conversion_mode
264except ImportError:
265 pass
266else:
267 if _os.name in ("nt", "ce"):
268 set_conversion_mode("mbcs", "ignore")
269 else:
270 set_conversion_mode("ascii", "strict")
271
272 class c_wchar_p(_SimpleCData):
273 _type_ = "Z"
274
275 class c_wchar(_SimpleCData):
276 _type_ = "u"
277
278 POINTER(c_wchar).from_param = c_wchar_p.from_param #_SimpleCData.c_wchar_p_from_param
279
280 def create_unicode_buffer(init, size=None):
281 """create_unicode_buffer(aString) -> character array
282 create_unicode_buffer(anInteger) -> character array
283 create_unicode_buffer(aString, anInteger) -> character array
284 """
Thomas Heller60831312007-07-12 19:06:25 +0000285 if isinstance(init, (str, bytes)):
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000286 if size is None:
287 size = len(init)+1
288 buftype = c_wchar * size
289 buf = buftype()
290 buf.value = init
291 return buf
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000292 elif isinstance(init, int):
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000293 buftype = c_wchar * init
294 buf = buftype()
295 return buf
Collin Wintera73bfee2007-08-30 03:47:13 +0000296 raise TypeError(init)
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000297
298POINTER(c_char).from_param = c_char_p.from_param #_SimpleCData.c_char_p_from_param
299
300# XXX Deprecated
301def SetPointerType(pointer, cls):
302 if _pointer_type_cache.get(cls, None) is not None:
Collin Wintera73bfee2007-08-30 03:47:13 +0000303 raise RuntimeError("This type already exists in the cache")
Guido van Rossum1b01e5c2006-08-19 02:45:06 +0000304 if id(pointer) not in _pointer_type_cache:
Collin Wintera73bfee2007-08-30 03:47:13 +0000305 raise RuntimeError("What's this???")
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000306 pointer.set_type(cls)
307 _pointer_type_cache[cls] = pointer
308 del _pointer_type_cache[id(pointer)]
309
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000310# XXX Deprecated
311def ARRAY(typ, len):
312 return typ * len
313
314################################################################
315
316
317class CDLL(object):
318 """An instance of this class represents a loaded dll/shared
319 library, exporting functions using the standard C calling
320 convention (named 'cdecl' on Windows).
321
322 The exported functions can be accessed as attributes, or by
323 indexing with the function name. Examples:
324
325 <obj>.qsort -> callable object
326 <obj>['qsort'] -> callable object
327
328 Calling the functions releases the Python GIL during the call and
Thomas Woutersed03b412007-08-28 21:37:11 +0000329 reacquires it afterwards.
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000330 """
Thomas Heller9cac7b62008-06-06 09:31:40 +0000331 _func_flags_ = _FUNCFLAG_CDECL
332 _func_restype_ = c_int
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000333
Thomas Heller9cac7b62008-06-06 09:31:40 +0000334 def __init__(self, name, mode=DEFAULT_MODE, handle=None,
335 use_errno=False,
336 use_last_error=False):
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000337 self._name = name
Thomas Heller9cac7b62008-06-06 09:31:40 +0000338 flags = self._func_flags_
339 if use_errno:
340 flags |= _FUNCFLAG_USE_ERRNO
341 if use_last_error:
342 flags |= _FUNCFLAG_USE_LASTERROR
343
344 class _FuncPtr(_CFuncPtr):
345 _flags_ = flags
346 _restype_ = self._func_restype_
347 self._FuncPtr = _FuncPtr
348
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000349 if handle is None:
350 self._handle = _dlopen(self._name, mode)
351 else:
352 self._handle = handle
353
354 def __repr__(self):
355 return "<%s '%s', handle %x at %x>" % \
356 (self.__class__.__name__, self._name,
Christian Heimesa37d4c62007-12-04 23:02:19 +0000357 (self._handle & (_sys.maxsize*2 + 1)),
358 id(self) & (_sys.maxsize*2 + 1))
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000359
360 def __getattr__(self, name):
361 if name.startswith('__') and name.endswith('__'):
Collin Wintera73bfee2007-08-30 03:47:13 +0000362 raise AttributeError(name)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000363 func = self.__getitem__(name)
364 setattr(self, name, func)
365 return func
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000366
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000367 def __getitem__(self, name_or_ordinal):
368 func = self._FuncPtr((name_or_ordinal, self))
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000369 if not isinstance(name_or_ordinal, int):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000370 func.__name__ = name_or_ordinal
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000371 return func
372
373class PyDLL(CDLL):
374 """This class represents the Python library itself. It allows to
375 access Python API functions. The GIL is not released, and
376 Python exceptions are handled correctly.
377 """
Thomas Heller9cac7b62008-06-06 09:31:40 +0000378 _func_flags_ = _FUNCFLAG_CDECL | _FUNCFLAG_PYTHONAPI
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000379
380if _os.name in ("nt", "ce"):
Tim Peterse8d09e52006-03-09 01:15:05 +0000381
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000382 class WinDLL(CDLL):
383 """This class represents a dll exporting functions using the
384 Windows stdcall calling convention.
385 """
Thomas Heller9cac7b62008-06-06 09:31:40 +0000386 _func_flags_ = _FUNCFLAG_STDCALL
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000387
388 # XXX Hm, what about HRESULT as normal parameter?
389 # Mustn't it derive from c_long then?
390 from _ctypes import _check_HRESULT, _SimpleCData
391 class HRESULT(_SimpleCData):
392 _type_ = "l"
393 # _check_retval_ is called with the function's result when it
394 # is used as restype. It checks for the FAILED bit, and
395 # raises a WindowsError if it is set.
396 #
397 # The _check_retval_ method is implemented in C, so that the
398 # method definition itself is not included in the traceback
399 # when it raises an error - that is what we want (and Python
400 # doesn't have a way to raise an exception in the caller's
401 # frame).
402 _check_retval_ = _check_HRESULT
Tim Peterse8d09e52006-03-09 01:15:05 +0000403
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000404 class OleDLL(CDLL):
405 """This class represents a dll exporting functions using the
406 Windows stdcall calling convention, and returning HRESULT.
407 HRESULT error values are automatically raised as WindowsError
408 exceptions.
409 """
Thomas Heller9cac7b62008-06-06 09:31:40 +0000410 _func_flags_ = _FUNCFLAG_STDCALL
411 _func_restype_ = HRESULT
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000412
Thomas Wouters477c8d52006-05-27 19:21:47 +0000413class LibraryLoader(object):
414 def __init__(self, dlltype):
415 self._dlltype = dlltype
416
417 def __getattr__(self, name):
418 if name[0] == '_':
419 raise AttributeError(name)
420 dll = self._dlltype(name)
421 setattr(self, name, dll)
422 return dll
423
424 def __getitem__(self, name):
425 return getattr(self, name)
426
427 def LoadLibrary(self, name):
428 return self._dlltype(name)
429
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000430cdll = LibraryLoader(CDLL)
431pydll = LibraryLoader(PyDLL)
432
433if _os.name in ("nt", "ce"):
434 pythonapi = PyDLL("python dll", None, _sys.dllhandle)
435elif _sys.platform == "cygwin":
436 pythonapi = PyDLL("libpython%d.%d.dll" % _sys.version_info[:2])
437else:
438 pythonapi = PyDLL(None)
439
440
441if _os.name in ("nt", "ce"):
442 windll = LibraryLoader(WinDLL)
443 oledll = LibraryLoader(OleDLL)
444
445 if _os.name == "nt":
446 GetLastError = windll.kernel32.GetLastError
447 else:
448 GetLastError = windll.coredll.GetLastError
Thomas Heller9cac7b62008-06-06 09:31:40 +0000449 from _ctypes import get_last_error, set_last_error
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000450
451 def WinError(code=None, descr=None):
452 if code is None:
453 code = GetLastError()
454 if descr is None:
455 descr = FormatError(code).strip()
456 return WindowsError(code, descr)
457
458_pointer_type_cache[None] = c_void_p
459
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000460if sizeof(c_uint) == sizeof(c_void_p):
461 c_size_t = c_uint
462elif sizeof(c_ulong) == sizeof(c_void_p):
463 c_size_t = c_ulong
Thomas Wouters89f507f2006-12-13 04:49:30 +0000464elif sizeof(c_ulonglong) == sizeof(c_void_p):
465 c_size_t = c_ulonglong
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000466
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000467# functions
468
469from _ctypes import _memmove_addr, _memset_addr, _string_at_addr, _cast_addr
470
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000471## void *memmove(void *, const void *, size_t);
472memmove = CFUNCTYPE(c_void_p, c_void_p, c_void_p, c_size_t)(_memmove_addr)
473
474## void *memset(void *, int, size_t)
475memset = CFUNCTYPE(c_void_p, c_void_p, c_int, c_size_t)(_memset_addr)
476
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000477def PYFUNCTYPE(restype, *argtypes):
478 class CFunctionType(_CFuncPtr):
479 _argtypes_ = argtypes
480 _restype_ = restype
481 _flags_ = _FUNCFLAG_CDECL | _FUNCFLAG_PYTHONAPI
482 return CFunctionType
Thomas Wouters477c8d52006-05-27 19:21:47 +0000483
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000484_cast = PYFUNCTYPE(py_object, c_void_p, py_object, py_object)(_cast_addr)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000485def cast(obj, typ):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000486 return _cast(obj, obj, typ)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000487
Thomas Heller47bc8092008-08-19 06:38:12 +0000488_string_at = PYFUNCTYPE(py_object, c_void_p, c_int)(_string_at_addr)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000489def string_at(ptr, size=-1):
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000490 """string_at(addr[, size]) -> string
491
492 Return the string at addr."""
493 return _string_at(ptr, size)
494
495try:
496 from _ctypes import _wstring_at_addr
497except ImportError:
498 pass
499else:
Thomas Heller47bc8092008-08-19 06:38:12 +0000500 _wstring_at = PYFUNCTYPE(py_object, c_void_p, c_int)(_wstring_at_addr)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000501 def wstring_at(ptr, size=-1):
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000502 """wstring_at(addr[, size]) -> string
503
504 Return the string at addr."""
505 return _wstring_at(ptr, size)
Tim Peterse8d09e52006-03-09 01:15:05 +0000506
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000507
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000508if _os.name in ("nt", "ce"): # COM stuff
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000509 def DllGetClassObject(rclsid, riid, ppv):
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000510 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000511 ccom = __import__("comtypes.server.inprocserver", globals(), locals(), ['*'])
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000512 except ImportError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000513 return -2147221231 # CLASS_E_CLASSNOTAVAILABLE
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000514 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000515 return ccom.DllGetClassObject(rclsid, riid, ppv)
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000516
517 def DllCanUnloadNow():
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000518 try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000519 ccom = __import__("comtypes.server.inprocserver", globals(), locals(), ['*'])
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000520 except ImportError:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000521 return 0 # S_OK
522 return ccom.DllCanUnloadNow()
Thomas Hellerbabddfc2006-03-08 19:56:54 +0000523
524from ctypes._endian import BigEndianStructure, LittleEndianStructure
525
526# Fill in specifically-sized types
527c_int8 = c_byte
528c_uint8 = c_ubyte
529for kind in [c_short, c_int, c_long, c_longlong]:
530 if sizeof(kind) == 2: c_int16 = kind
531 elif sizeof(kind) == 4: c_int32 = kind
532 elif sizeof(kind) == 8: c_int64 = kind
533for kind in [c_ushort, c_uint, c_ulong, c_ulonglong]:
534 if sizeof(kind) == 2: c_uint16 = kind
535 elif sizeof(kind) == 4: c_uint32 = kind
536 elif sizeof(kind) == 8: c_uint64 = kind
537del(kind)
Thomas Heller674e9382007-08-31 13:06:44 +0000538
539# XXX for whatever reasons, creating the first instance of a callback
540# function is needed for the unittests on Win64 to succeed. This MAY
541# be a compiler bug, since the problem occurs only when _ctypes is
542# compiled with the MS SDK compiler. Or an uninitialized variable?
543CFUNCTYPE(c_int)(lambda: None)