Debian Codegraph @

Doc/library/ctypes.rst

raw
1 :mod:`!ctypes` --- A foreign function library for Python
2 ========================================================
3
4 .. module:: ctypes
5 :synopsis: A foreign function library for Python.
6
7 .. moduleauthor:: Thomas Heller <[email protected]>
8
9 **Source code:** :source:`Lib/ctypes`
10
11 --------------
12
13 :mod:`ctypes` is a foreign function library for Python. It provides C compatible
14 data types, and allows calling functions in DLLs or shared libraries. It can be
15 used to wrap these libraries in pure Python.
16
17 .. warning::
18
19 :mod:`!ctypes` provides low-level access to native libraries and the
20 process's memory, bypassing Python's safety mechanisms and allowing
21 execution of arbitrary native code.
22 Incorrect use can corrupt data and objects, reveal sensitive information,
23 cause crashes, or otherwise compromise the running process.
24
25
26 .. _ctypes-ctypes-tutorial:
27
28 ctypes tutorial
29 ---------------
30
31 Note: The code samples in this tutorial use :mod:`doctest` to make sure that
32 they actually work. Since some code samples behave differently under Linux,
33 Windows, or macOS, they contain doctest directives in comments.
34
35 Note: Some code samples reference the ctypes :class:`c_int` type. On platforms
36 where ``sizeof(long) == sizeof(int)`` it is an alias to :class:`c_long`.
37 So, you should not be confused if :class:`c_long` is printed if you would expect
38 :class:`c_int` --- they are actually the same type.
39
40 .. _ctypes-loading-dynamic-link-libraries:
41
42 Loading dynamic link libraries
43 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
44
45 :mod:`ctypes` exports the *cdll*, and on Windows *windll* and *oledll*
46 objects, for loading dynamic link libraries.
47
48 You load libraries by accessing them as attributes of these objects. *cdll*
49 loads libraries which export functions using the standard ``cdecl`` calling
50 convention, while *windll* libraries call functions using the ``stdcall``
51 calling convention. *oledll* also uses the ``stdcall`` calling convention, and
52 assumes the functions return a Windows :c:type:`!HRESULT` error code. The error
53 code is used to automatically raise an :class:`OSError` exception when the
54 function call fails.
55
56 .. versionchanged:: 3.3
57 Windows errors used to raise :exc:`WindowsError`, which is now an alias
58 of :exc:`OSError`.
59
60
61 Here are some examples for Windows. Note that ``msvcrt`` is the MS standard C
62 library containing most standard C functions, and uses the ``cdecl`` calling
63 convention::
64
65 >>> from ctypes import *
66 >>> print(windll.kernel32) # doctest: +WINDOWS
67 <WinDLL 'kernel32', handle ... at ...>
68 >>> print(cdll.msvcrt) # doctest: +WINDOWS
69 <CDLL 'msvcrt', handle ... at ...>
70 >>> libc = cdll.msvcrt # doctest: +WINDOWS
71 >>>
72
73 Windows appends the usual ``.dll`` file suffix automatically.
74
75 .. note::
76 Accessing the standard C library through ``cdll.msvcrt`` will use an
77 outdated version of the library that may be incompatible with the one
78 being used by Python. Where possible, use native Python functionality,
79 or else import and use the ``msvcrt`` module.
80
81 On Linux, it is required to specify the filename *including* the extension to
82 load a library, so attribute access can not be used to load libraries. Either the
83 :meth:`~LibraryLoader.LoadLibrary` method of the dll loaders should be used,
84 or you should load the library by creating an instance of CDLL by calling
85 the constructor::
86
87 >>> cdll.LoadLibrary("libc.so.6") # doctest: +LINUX
88 <CDLL 'libc.so.6', handle ... at ...>
89 >>> libc = CDLL("libc.so.6") # doctest: +LINUX
90 >>> libc # doctest: +LINUX
91 <CDLL 'libc.so.6', handle ... at ...>
92 >>>
93
94 .. XXX Add section for macOS.
95
96
97 .. _ctypes-accessing-functions-from-loaded-dlls:
98
99 Accessing functions from loaded dlls
100 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
101
102 Functions are accessed as attributes of dll objects::
103
104 >>> libc.printf
105 <_FuncPtr object at 0x...>
106 >>> print(windll.kernel32.GetModuleHandleA) # doctest: +WINDOWS
107 <_FuncPtr object at 0x...>
108 >>> print(windll.kernel32.MyOwnFunction) # doctest: +WINDOWS
109 Traceback (most recent call last):
110 File "<stdin>", line 1, in <module>
111 File "ctypes.py", line 239, in __getattr__
112 func = _StdcallFuncPtr(name, self)
113 AttributeError: function 'MyOwnFunction' not found
114 >>>
115
116 Note that win32 system dlls like ``kernel32`` and ``user32`` often export ANSI
117 as well as UNICODE versions of a function. The UNICODE version is exported with
118 a ``W`` appended to the name, while the ANSI version is exported with an ``A``
119 appended to the name. The win32 ``GetModuleHandle`` function, which returns a
120 *module handle* for a given module name, has the following C prototype, and a
121 macro is used to expose one of them as ``GetModuleHandle`` depending on whether
122 UNICODE is defined or not::
123
124 /* ANSI version */
125 HMODULE GetModuleHandleA(LPCSTR lpModuleName);
126 /* UNICODE version */
127 HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
128
129 *windll* does not try to select one of them by magic, you must access the
130 version you need by specifying ``GetModuleHandleA`` or ``GetModuleHandleW``
131 explicitly, and then call it with bytes or string objects respectively.
132
133 Sometimes, dlls export functions with names which aren't valid Python
134 identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use
135 :func:`getattr` to retrieve the function::
136
137 >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") # doctest: +WINDOWS
138 <_FuncPtr object at 0x...>
139 >>>
140
141 On Windows, some dlls export functions not by name but by ordinal. These
142 functions can be accessed by indexing the dll object with the ordinal number::
143
144 >>> cdll.kernel32[1] # doctest: +WINDOWS
145 <_FuncPtr object at 0x...>
146 >>> cdll.kernel32[0] # doctest: +WINDOWS
147 Traceback (most recent call last):
148 File "<stdin>", line 1, in <module>
149 File "ctypes.py", line 310, in __getitem__
150 func = _StdcallFuncPtr(name, self)
151 AttributeError: function ordinal 0 not found
152 >>>
153
154
155 .. _ctypes-calling-functions:
156
157 Calling functions
158 ^^^^^^^^^^^^^^^^^
159
160 You can call these functions like any other Python callable. This example uses
161 the ``rand()`` function, which takes no arguments and returns a pseudo-random integer::
162
163 >>> print(libc.rand()) # doctest: +SKIP
164 1804289383
165
166 On Windows, you can call the ``GetModuleHandleA()`` function, which returns a win32 module
167 handle (passing ``None`` as single argument to call it with a ``NULL`` pointer)::
168
169 >>> print(hex(windll.kernel32.GetModuleHandleA(None))) # doctest: +WINDOWS
170 0x1d000000
171 >>>
172
173 :exc:`ValueError` is raised when you call an ``stdcall`` function with the
174 ``cdecl`` calling convention, or vice versa::
175
176 >>> cdll.kernel32.GetModuleHandleA(None) # doctest: +WINDOWS
177 Traceback (most recent call last):
178 File "<stdin>", line 1, in <module>
179 ValueError: Procedure probably called with not enough arguments (4 bytes missing)
180 >>>
181
182 >>> windll.msvcrt.printf(b"spam") # doctest: +WINDOWS
183 Traceback (most recent call last):
184 File "<stdin>", line 1, in <module>
185 ValueError: Procedure probably called with too many arguments (4 bytes in excess)
186 >>>
187
188 To find out the correct calling convention you have to look into the C header
189 file or the documentation for the function you want to call.
190
191 On Windows, :mod:`ctypes` uses win32 structured exception handling to prevent
192 crashes from general protection faults when functions are called with invalid
193 argument values::
194
195 >>> windll.kernel32.GetModuleHandleA(32) # doctest: +WINDOWS
196 Traceback (most recent call last):
197 File "<stdin>", line 1, in <module>
198 OSError: exception: access violation reading 0x00000020
199 >>>
200
201 The :mod:`faulthandler` module can help debug crashes,
202 such as segmentation faults produced by erroneous C library calls.
203
204 ``None``, integers, bytes objects and (unicode) strings are the only native
205 Python objects that can directly be used as parameters in these function calls.
206 ``None`` is passed as a C ``NULL`` pointer, bytes objects and strings are passed
207 as pointer to the memory block that contains their data (:c:expr:`char *` or
208 :c:expr:`wchar_t *`). Python integers are passed as the platform's default C
209 :c:expr:`int` type, their value is masked to fit into the C type.
210
211 Before we move on calling functions with other parameter types, we have to learn
212 more about :mod:`ctypes` data types.
213
214
215 .. _ctypes-fundamental-data-types:
216
217 Fundamental data types
218 ^^^^^^^^^^^^^^^^^^^^^^
219
220 :mod:`ctypes` defines a number of primitive C compatible data types:
221
222 +----------------------+------------------------------------------+----------------------------+
223 | ctypes type | C type | Python type |
224 +======================+==========================================+============================+
225 | :class:`c_bool` | :c:expr:`_Bool` | bool (1) |
226 +----------------------+------------------------------------------+----------------------------+
227 | :class:`c_char` | :c:expr:`char` | 1-character bytes object |
228 +----------------------+------------------------------------------+----------------------------+
229 | :class:`c_wchar` | :c:type:`wchar_t` | 1-character string |
230 +----------------------+------------------------------------------+----------------------------+
231 | :class:`c_byte` | :c:expr:`char` | int |
232 +----------------------+------------------------------------------+----------------------------+
233 | :class:`c_ubyte` | :c:expr:`unsigned char` | int |
234 +----------------------+------------------------------------------+----------------------------+
235 | :class:`c_short` | :c:expr:`short` | int |
236 +----------------------+------------------------------------------+----------------------------+
237 | :class:`c_ushort` | :c:expr:`unsigned short` | int |
238 +----------------------+------------------------------------------+----------------------------+
239 | :class:`c_int` | :c:expr:`int` | int |
240 +----------------------+------------------------------------------+----------------------------+
241 | :class:`c_int8` | :c:type:`int8_t` | int |
242 +----------------------+------------------------------------------+----------------------------+
243 | :class:`c_int16` | :c:type:`int16_t` | int |
244 +----------------------+------------------------------------------+----------------------------+
245 | :class:`c_int32` | :c:type:`int32_t` | int |
246 +----------------------+------------------------------------------+----------------------------+
247 | :class:`c_int64` | :c:type:`int64_t` | int |
248 +----------------------+------------------------------------------+----------------------------+
249 | :class:`c_uint` | :c:expr:`unsigned int` | int |
250 +----------------------+------------------------------------------+----------------------------+
251 | :class:`c_uint8` | :c:type:`uint8_t` | int |
252 +----------------------+------------------------------------------+----------------------------+
253 | :class:`c_uint16` | :c:type:`uint16_t` | int |
254 +----------------------+------------------------------------------+----------------------------+
255 | :class:`c_uint32` | :c:type:`uint32_t` | int |
256 +----------------------+------------------------------------------+----------------------------+
257 | :class:`c_uint64` | :c:type:`uint64_t` | int |
258 +----------------------+------------------------------------------+----------------------------+
259 | :class:`c_long` | :c:expr:`long` | int |
260 +----------------------+------------------------------------------+----------------------------+
261 | :class:`c_ulong` | :c:expr:`unsigned long` | int |
262 +----------------------+------------------------------------------+----------------------------+
263 | :class:`c_longlong` | :c:expr:`__int64` or :c:expr:`long long` | int |
264 +----------------------+------------------------------------------+----------------------------+
265 | :class:`c_ulonglong` | :c:expr:`unsigned __int64` or | int |
266 | | :c:expr:`unsigned long long` | |
267 +----------------------+------------------------------------------+----------------------------+
268 | :class:`c_size_t` | :c:type:`size_t` | int |
269 +----------------------+------------------------------------------+----------------------------+
270 | :class:`c_ssize_t` | :c:type:`ssize_t` or | int |
271 | | :c:expr:`Py_ssize_t` | |
272 +----------------------+------------------------------------------+----------------------------+
273 | :class:`c_time_t` | :c:type:`time_t` | int |
274 +----------------------+------------------------------------------+----------------------------+
275 | :class:`c_float` | :c:expr:`float` | float |
276 +----------------------+------------------------------------------+----------------------------+
277 | :class:`c_double` | :c:expr:`double` | float |
278 +----------------------+------------------------------------------+----------------------------+
279 | :class:`c_longdouble`| :c:expr:`long double` | float |
280 +----------------------+------------------------------------------+----------------------------+
281 | :class:`c_char_p` | :c:expr:`char *` (NUL terminated) | bytes object or ``None`` |
282 +----------------------+------------------------------------------+----------------------------+
283 | :class:`c_wchar_p` | :c:expr:`wchar_t *` (NUL terminated) | string or ``None`` |
284 +----------------------+------------------------------------------+----------------------------+
285 | :class:`c_void_p` | :c:expr:`void *` | int or ``None`` |
286 +----------------------+------------------------------------------+----------------------------+
287
288 (1)
289 The constructor accepts any object with a truth value.
290
291 All these types can be created by calling them with an optional initializer of
292 the correct type and value::
293
294 >>> c_int()
295 c_long(0)
296 >>> c_wchar_p("Hello, World")
297 c_wchar_p(140018365411392)
298 >>> c_ushort(-3)
299 c_ushort(65533)
300 >>>
301
302 Since these types are mutable, their value can also be changed afterwards::
303
304 >>> i = c_int(42)
305 >>> print(i)
306 c_long(42)
307 >>> print(i.value)
308 42
309 >>> i.value = -99
310 >>> print(i.value)
311 -99
312 >>>
313
314 Assigning a new value to instances of the pointer types :class:`c_char_p`,
315 :class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they
316 point to, *not the contents* of the memory block (of course not, because Python
317 string objects are immutable)::
318
319 >>> s = "Hello, World"
320 >>> c_s = c_wchar_p(s)
321 >>> print(c_s)
322 c_wchar_p(139966785747344)
323 >>> print(c_s.value)
324 Hello World
325 >>> c_s.value = "Hi, there"
326 >>> print(c_s) # the memory location has changed
327 c_wchar_p(139966783348904)
328 >>> print(c_s.value)
329 Hi, there
330 >>> print(s) # first object is unchanged
331 Hello, World
332 >>>
333
334 You should be careful, however, not to pass them to functions expecting pointers
335 to mutable memory. If you need mutable memory blocks, ctypes has a
336 :func:`create_string_buffer` function which creates these in various ways. The
337 current memory block contents can be accessed (or changed) with the ``raw``
338 property; if you want to access it as NUL terminated string, use the ``value``
339 property::
340
341 >>> from ctypes import *
342 >>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes
343 >>> print(sizeof(p), repr(p.raw))
344 3 b'\x00\x00\x00'
345 >>> p = create_string_buffer(b"Hello") # create a buffer containing a NUL terminated string
346 >>> print(sizeof(p), repr(p.raw))
347 6 b'Hello\x00'
348 >>> print(repr(p.value))
349 b'Hello'
350 >>> p = create_string_buffer(b"Hello", 10) # create a 10 byte buffer
351 >>> print(sizeof(p), repr(p.raw))
352 10 b'Hello\x00\x00\x00\x00\x00'
353 >>> p.value = b"Hi"
354 >>> print(sizeof(p), repr(p.raw))
355 10 b'Hi\x00lo\x00\x00\x00\x00\x00'
356 >>>
357
358 The :func:`create_string_buffer` function replaces the old :func:`!c_buffer`
359 function (which is still available as an alias). To create a mutable memory
360 block containing unicode characters of the C type :c:type:`wchar_t`, use the
361 :func:`create_unicode_buffer` function.
362
363
364 .. _ctypes-calling-functions-continued:
365
366 Calling functions, continued
367 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
368
369 Note that printf prints to the real standard output channel, *not* to
370 :data:`sys.stdout`, so these examples will only work at the console prompt, not
371 from within *IDLE* or *PythonWin*::
372
373 >>> printf = libc.printf
374 >>> printf(b"Hello, %s\n", b"World!")
375 Hello, World!
376 14
377 >>> printf(b"Hello, %S\n", "World!")
378 Hello, World!
379 14
380 >>> printf(b"%d bottles of beer\n", 42)
381 42 bottles of beer
382 19
383 >>> printf(b"%f bottles of beer\n", 42.5)
384 Traceback (most recent call last):
385 File "<stdin>", line 1, in <module>
386 ctypes.ArgumentError: argument 2: TypeError: Don't know how to convert parameter 2
387 >>>
388
389 As has been mentioned before, all Python types except integers, strings, and
390 bytes objects have to be wrapped in their corresponding :mod:`ctypes` type, so
391 that they can be converted to the required C data type::
392
393 >>> printf(b"An int %d, a double %f\n", 1234, c_double(3.14))
394 An int 1234, a double 3.140000
395 31
396 >>>
397
398 .. _ctypes-calling-variadic-functions:
399
400 Calling variadic functions
401 ^^^^^^^^^^^^^^^^^^^^^^^^^^
402
403 On a lot of platforms calling variadic functions through ctypes is exactly the same
404 as calling functions with a fixed number of parameters. On some platforms, and in
405 particular ARM64 for Apple Platforms, the calling convention for variadic functions
406 is different than that for regular functions.
407
408 On those platforms it is required to specify the :attr:`~_CFuncPtr.argtypes`
409 attribute for the regular, non-variadic, function arguments:
410
411 .. code-block:: python3
412
413 libc.printf.argtypes = [ctypes.c_char_p]
414
415 Because specifying the attribute does not inhibit portability it is advised to always
416 specify :attr:`~_CFuncPtr.argtypes` for all variadic functions.
417
418
419 .. _ctypes-calling-functions-with-own-custom-data-types:
420
421 Calling functions with your own custom data types
422 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
423
424 You can also customize :mod:`ctypes` argument conversion to allow instances of
425 your own classes be used as function arguments. :mod:`ctypes` looks for an
426 :attr:`!_as_parameter_` attribute and uses this as the function argument. The
427 attribute must be an integer, string, bytes, a :mod:`ctypes` instance, or an
428 object with an :attr:`!_as_parameter_` attribute::
429
430 >>> class Bottles:
431 ... def __init__(self, number):
432 ... self._as_parameter_ = number
433 ...
434 >>> bottles = Bottles(42)
435 >>> printf(b"%d bottles of beer\n", bottles)
436 42 bottles of beer
437 19
438 >>>
439
440 If you don't want to store the instance's data in the :attr:`!_as_parameter_`
441 instance variable, you could define a :deco:`property` which makes the
442 attribute available on request.
443
444
445 .. _ctypes-specifying-required-argument-types:
446
447 Specifying the required argument types (function prototypes)
448 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
449
450 It is possible to specify the required argument types of functions exported from
451 DLLs by setting the :attr:`~_CFuncPtr.argtypes` attribute.
452
453 :attr:`~_CFuncPtr.argtypes` must be a sequence of C data types (the :func:`!printf` function is
454 probably not a good example here, because it takes a variable number and
455 different types of parameters depending on the format string, on the other hand
456 this is quite handy to experiment with this feature)::
457
458 >>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
459 >>> printf(b"String '%s', Int %d, Double %f\n", b"Hi", 10, 2.2)
460 String 'Hi', Int 10, Double 2.200000
461 37
462 >>>
463
464 Specifying a format protects against incompatible argument types (just as a
465 prototype for a C function), and tries to convert the arguments to valid types::
466
467 >>> printf(b"%d %d %d", 1, 2, 3)
468 Traceback (most recent call last):
469 File "<stdin>", line 1, in <module>
470 ctypes.ArgumentError: argument 2: TypeError: 'int' object cannot be interpreted as ctypes.c_char_p
471 >>> printf(b"%s %d %f\n", b"X", 2, 3)
472 X 2 3.000000
473 13
474 >>>
475
476 If you have defined your own classes which you pass to function calls, you have
477 to implement a :meth:`~_CData.from_param` class method for them to be able to use them
478 in the :attr:`~_CFuncPtr.argtypes` sequence. The :meth:`~_CData.from_param` class method receives
479 the Python object passed to the function call, it should do a typecheck or
480 whatever is needed to make sure this object is acceptable, and then return the
481 object itself, its :attr:`!_as_parameter_` attribute, or whatever you want to
482 pass as the C function argument in this case. Again, the result should be an
483 integer, string, bytes, a :mod:`ctypes` instance, or an object with an
484 :attr:`!_as_parameter_` attribute.
485
486
487 .. _ctypes-return-types:
488
489 Return types
490 ^^^^^^^^^^^^
491
492 .. testsetup::
493
494 from ctypes import CDLL, c_char, c_char_p
495 from ctypes.util import find_library
496 libc = CDLL(find_library('c'))
497 strchr = libc.strchr
498
499
500 By default functions are assumed to return the C :c:expr:`int` type. Other
501 return types can be specified by setting the :attr:`~_CFuncPtr.restype` attribute of the
502 function object.
503
504 The C prototype of :c:func:`time` is ``time_t time(time_t *)``. Because :c:type:`time_t`
505 might be of a different type than the default return type :c:expr:`int`, you should
506 specify the :attr:`!restype` attribute::
507
508 >>> libc.time.restype = c_time_t
509
510 The argument types can be specified using :attr:`~_CFuncPtr.argtypes`::
511
512 >>> libc.time.argtypes = (POINTER(c_time_t),)
513
514 To call the function with a ``NULL`` pointer as first argument, use ``None``::
515
516 >>> print(libc.time(None)) # doctest: +SKIP
517 1150640792
518
519 Here is a more advanced example, it uses the :func:`!strchr` function, which expects
520 a string pointer and a char, and returns a pointer to a string::
521
522 >>> strchr = libc.strchr
523 >>> strchr(b"abcdef", ord("d")) # doctest: +SKIP
524 8059983
525 >>> strchr.restype = c_char_p # c_char_p is a pointer to a string
526 >>> strchr(b"abcdef", ord("d"))
527 b'def'
528 >>> print(strchr(b"abcdef", ord("x")))
529 None
530 >>>
531
532 If you want to avoid the :func:`ord("x") <ord>` calls above, you can set the
533 :attr:`~_CFuncPtr.argtypes` attribute, and the second argument will be converted from a
534 single character Python bytes object into a C char:
535
536 .. doctest::
537
538 >>> strchr.restype = c_char_p
539 >>> strchr.argtypes = [c_char_p, c_char]
540 >>> strchr(b"abcdef", b"d")
541 b'def'
542 >>> strchr(b"abcdef", b"def")
543 Traceback (most recent call last):
544 ctypes.ArgumentError: argument 2: TypeError: one character bytes, bytearray or integer expected
545 >>> print(strchr(b"abcdef", b"x"))
546 None
547 >>> strchr(b"abcdef", b"d")
548 b'def'
549 >>>
550
551 You can also use a callable Python object (a function or a class for example) as
552 the :attr:`~_CFuncPtr.restype` attribute, if the foreign function returns an integer. The
553 callable will be called with the *integer* the C function returns, and the
554 result of this call will be used as the result of your function call. This is
555 useful to check for error return values and automatically raise an exception::
556
557 >>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
558 >>> def ValidHandle(value):
559 ... if value == 0:
560 ... raise WinError()
561 ... return value
562 ...
563 >>>
564 >>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS
565 >>> GetModuleHandle(None) # doctest: +WINDOWS
566 486539264
567 >>> GetModuleHandle("something silly") # doctest: +WINDOWS
568 Traceback (most recent call last):
569 File "<stdin>", line 1, in <module>
570 File "<stdin>", line 3, in ValidHandle
571 OSError: [Errno 126] The specified module could not be found.
572 >>>
573
574 ``WinError`` is a function which will call Windows ``FormatMessage()`` api to
575 get the string representation of an error code, and *returns* an exception.
576 ``WinError`` takes an optional error code parameter, if no one is used, it calls
577 :func:`GetLastError` to retrieve it.
578
579 Please note that a much more powerful error checking mechanism is available
580 through the :attr:`~_CFuncPtr.errcheck` attribute;
581 see the reference manual for details.
582
583
584 .. _ctypes-passing-pointers:
585
586 Passing pointers (or: passing parameters by reference)
587 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
588
589 Sometimes a C api function expects a *pointer* to a data type as parameter,
590 probably to write into the corresponding location, or if the data is too large
591 to be passed by value. This is also known as *passing parameters by reference*.
592
593 :mod:`ctypes` exports the :func:`byref` function which is used to pass parameters
594 by reference. The same effect can be achieved with the :func:`pointer` function,
595 although :func:`pointer` does a lot more work since it constructs a real pointer
596 object, so it is faster to use :func:`byref` if you don't need the pointer
597 object in Python itself::
598
599 >>> i = c_int()
600 >>> f = c_float()
601 >>> s = create_string_buffer(b'\000' * 32)
602 >>> print(i.value, f.value, repr(s.value))
603 0 0.0 b''
604 >>> libc.sscanf(b"1 3.14 Hello", b"%d %f %s",
605 ... byref(i), byref(f), s)
606 3
607 >>> print(i.value, f.value, repr(s.value))
608 1 3.1400001049 b'Hello'
609 >>>
610
611
612 .. _ctypes-structures-unions:
613
614 Structures and unions
615 ^^^^^^^^^^^^^^^^^^^^^
616
617 Structures and unions must derive from the :class:`Structure` and :class:`Union`
618 base classes which are defined in the :mod:`ctypes` module. Each subclass must
619 define a :attr:`~Structure._fields_` attribute. :attr:`!_fields_` must be a list of
620 *2-tuples*, containing a *field name* and a *field type*.
621
622 The field type must be a :mod:`ctypes` type like :class:`c_int`, or any other
623 derived :mod:`ctypes` type: structure, union, array, pointer.
624
625 Here is a simple example of a POINT structure, which contains two integers named
626 *x* and *y*, and also shows how to initialize a structure in the constructor::
627
628 >>> from ctypes import *
629 >>> class POINT(Structure):
630 ... _fields_ = [("x", c_int),
631 ... ("y", c_int)]
632 ...
633 >>> point = POINT(10, 20)
634 >>> print(point.x, point.y)
635 10 20
636 >>> point = POINT(y=5)
637 >>> print(point.x, point.y)
638 0 5
639 >>> POINT(1, 2, 3)
640 Traceback (most recent call last):
641 File "<stdin>", line 1, in <module>
642 TypeError: too many initializers
643 >>>
644
645 You can, however, build much more complicated structures. A structure can
646 itself contain other structures by using a structure as a field type.
647
648 Here is a RECT structure which contains two POINTs named *upperleft* and
649 *lowerright*::
650
651 >>> class RECT(Structure):
652 ... _fields_ = [("upperleft", POINT),
653 ... ("lowerright", POINT)]
654 ...
655 >>> rc = RECT(point)
656 >>> print(rc.upperleft.x, rc.upperleft.y)
657 0 5
658 >>> print(rc.lowerright.x, rc.lowerright.y)
659 0 0
660 >>>
661
662 Nested structures can also be initialized in the constructor in several ways::
663
664 >>> r = RECT(POINT(1, 2), POINT(3, 4))
665 >>> r = RECT((1, 2), (3, 4))
666
667 Field :term:`descriptor`\s can be retrieved from the *class*, they are useful
668 for debugging because they can provide useful information::
669
670 >>> print(POINT.x)
671 <Field type=c_long, ofs=0, size=4>
672 >>> print(POINT.y)
673 <Field type=c_long, ofs=4, size=4>
674 >>>
675
676
677 .. _ctypes-structureunion-alignment-byte-order:
678
679 .. warning::
680
681 :mod:`ctypes` does not support passing unions or structures with bit-fields
682 to functions by value. While this may work on 32-bit x86, it's not
683 guaranteed by the library to work in the general case. Unions and
684 structures with bit-fields should always be passed to functions by pointer.
685
686 Structure/union alignment and byte order
687 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
688
689 By default, Structure and Union fields are aligned in the same way the C
690 compiler does it. It is possible to override this behavior by specifying a
691 :attr:`~Structure._pack_` class attribute in the subclass definition.
692 This must be set to a positive integer and specifies the maximum alignment for the fields.
693 This is what ``#pragma pack(n)`` also does in MSVC.
694 It is also possible to set a minimum alignment for how the subclass itself is packed in the
695 same way ``#pragma align(n)`` works in MSVC.
696 This can be achieved by specifying a :attr:`~Structure._align_` class attribute
697 in the subclass definition.
698
699 :mod:`ctypes` uses the native byte order for Structures and Unions. To build
700 structures with non-native byte order, you can use one of the
701 :class:`BigEndianStructure`, :class:`LittleEndianStructure`,
702 :class:`BigEndianUnion`, and :class:`LittleEndianUnion` base classes. These
703 classes cannot contain pointer fields.
704
705
706 .. _ctypes-bit-fields-in-structures-unions:
707
708 Bit fields in structures and unions
709 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
710
711 It is possible to create structures and unions containing bit fields. Bit fields
712 are only possible for integer fields, the bit width is specified as the third
713 item in the :attr:`~Structure._fields_` tuples::
714
715 >>> class Int(Structure):
716 ... _fields_ = [("first_16", c_int, 16),
717 ... ("second_16", c_int, 16)]
718 ...
719 >>> print(Int.first_16)
720 <Field type=c_long, ofs=0:0, bits=16>
721 >>> print(Int.second_16)
722 <Field type=c_long, ofs=0:16, bits=16>
723 >>>
724
725
726 .. _ctypes-arrays:
727
728 Arrays
729 ^^^^^^
730
731 Arrays are sequences, containing a fixed number of instances of the same type.
732
733 The recommended way to create array types is by multiplying a data type with a
734 positive integer::
735
736 TenPointsArrayType = POINT * 10
737
738 Here is an example of a somewhat artificial data type, a structure containing 4
739 POINTs among other stuff::
740
741 >>> from ctypes import *
742 >>> class POINT(Structure):
743 ... _fields_ = ("x", c_int), ("y", c_int)
744 ...
745 >>> class MyStruct(Structure):
746 ... _fields_ = [("a", c_int),
747 ... ("b", c_float),
748 ... ("point_array", POINT * 4)]
749 >>>
750 >>> print(len(MyStruct().point_array))
751 4
752 >>>
753
754 Instances are created in the usual way, by calling the class::
755
756 arr = TenPointsArrayType()
757 for pt in arr:
758 print(pt.x, pt.y)
759
760 The above code print a series of ``0 0`` lines, because the array contents is
761 initialized to zeros.
762
763 Initializers of the correct type can also be specified::
764
765 >>> from ctypes import *
766 >>> TenIntegers = c_int * 10
767 >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
768 >>> print(ii)
769 <c_long_Array_10 object at 0x...>
770 >>> for i in ii: print(i, end=" ")
771 ...
772 1 2 3 4 5 6 7 8 9 10
773 >>>
774
775
776 .. _ctypes-pointers:
777
778 Pointers
779 ^^^^^^^^
780
781 Pointer instances are created by calling the :func:`pointer` function on a
782 :mod:`ctypes` type::
783
784 >>> from ctypes import *
785 >>> i = c_int(42)
786 >>> pi = pointer(i)
787 >>>
788
789 Pointer instances have a :attr:`~_Pointer.contents` attribute which
790 returns the object to which the pointer points, the ``i`` object above::
791
792 >>> pi.contents
793 c_long(42)
794 >>>
795
796 Note that :mod:`ctypes` does not have OOR (original object return), it constructs a
797 new, equivalent object each time you retrieve an attribute::
798
799 >>> pi.contents is i
800 False
801 >>> pi.contents is pi.contents
802 False
803 >>>
804
805 Assigning another :class:`c_int` instance to the pointer's contents attribute
806 would cause the pointer to point to the memory location where this is stored::
807
808 >>> i = c_int(99)
809 >>> pi.contents = i
810 >>> pi.contents
811 c_long(99)
812 >>>
813
814 .. XXX Document dereferencing pointers, and that it is preferred over the
815 .contents attribute.
816
817 Pointer instances can also be indexed with integers::
818
819 >>> pi[0]
820 99
821 >>>
822
823 Assigning to an integer index changes the pointed to value::
824
825 >>> print(i)
826 c_long(99)
827 >>> pi[0] = 22
828 >>> print(i)
829 c_long(22)
830 >>>
831
832 It is also possible to use indexes different from 0, but you must know what
833 you're doing, just as in C: You can access or change arbitrary memory locations.
834 Generally you only use this feature if you receive a pointer from a C function,
835 and you *know* that the pointer actually points to an array instead of a single
836 item.
837
838 Behind the scenes, the :func:`pointer` function does more than simply create
839 pointer instances, it has to create pointer *types* first. This is done with the
840 :func:`POINTER` function, which accepts any :mod:`ctypes` type, and returns a
841 new type::
842
843 >>> PI = POINTER(c_int)
844 >>> PI
845 <class 'ctypes.LP_c_long'>
846 >>> PI(42)
847 Traceback (most recent call last):
848 File "<stdin>", line 1, in <module>
849 TypeError: expected c_long instead of int
850 >>> PI(c_int(42))
851 <ctypes.LP_c_long object at 0x...>
852 >>>
853
854 Calling the pointer type without an argument creates a ``NULL`` pointer.
855 ``NULL`` pointers have a ``False`` boolean value::
856
857 >>> null_ptr = POINTER(c_int)()
858 >>> print(bool(null_ptr))
859 False
860 >>>
861
862 :mod:`ctypes` checks for ``NULL`` when dereferencing pointers (but dereferencing
863 invalid non-\ ``NULL`` pointers would crash Python)::
864
865 >>> null_ptr[0]
866 Traceback (most recent call last):
867 ....
868 ValueError: NULL pointer access
869 >>>
870
871 >>> null_ptr[0] = 1234
872 Traceback (most recent call last):
873 ....
874 ValueError: NULL pointer access
875 >>>
876
877
878 .. _ctypes-type-conversions:
879
880 Type conversions
881 ^^^^^^^^^^^^^^^^
882
883 Usually, ctypes does strict type checking. This means, if you have
884 ``POINTER(c_int)`` in the :attr:`~_CFuncPtr.argtypes` list of a function or as the type of
885 a member field in a structure definition, only instances of exactly the same
886 type are accepted. There are some exceptions to this rule, where ctypes accepts
887 other objects. For example, you can pass compatible array instances instead of
888 pointer types. So, for ``POINTER(c_int)``, ctypes accepts an array of c_int::
889
890 >>> class Bar(Structure):
891 ... _fields_ = [("count", c_int), ("values", POINTER(c_int))]
892 ...
893 >>> bar = Bar()
894 >>> bar.values = (c_int * 3)(1, 2, 3)
895 >>> bar.count = 3
896 >>> for i in range(bar.count):
897 ... print(bar.values[i])
898 ...
899 1
900 2
901 3
902 >>>
903
904 In addition, if a function argument is explicitly declared to be a pointer type
905 (such as ``POINTER(c_int)``) in :attr:`~_CFuncPtr.argtypes`, an object of the pointed
906 type (``c_int`` in this case) can be passed to the function. ctypes will apply
907 the required :func:`byref` conversion in this case automatically.
908
909 To set a POINTER type field to ``NULL``, you can assign ``None``::
910
911 >>> bar.values = None
912 >>>
913
914 .. XXX list other conversions...
915
916 Sometimes you have instances of incompatible types. In C, you can cast one type
917 into another type. :mod:`ctypes` provides a :func:`cast` function which can be
918 used in the same way. The ``Bar`` structure defined above accepts
919 ``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field,
920 but not instances of other types::
921
922 >>> bar.values = (c_byte * 4)()
923 Traceback (most recent call last):
924 File "<stdin>", line 1, in <module>
925 TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
926 >>>
927
928 For these cases, the :func:`cast` function is handy.
929
930 The :func:`cast` function can be used to cast a ctypes instance into a pointer
931 to a different ctypes data type. :func:`cast` takes two parameters, a ctypes
932 object that is or can be converted to a pointer of some kind, and a ctypes
933 pointer type. It returns an instance of the second argument, which references
934 the same memory block as the first argument::
935
936 >>> a = (c_byte * 4)()
937 >>> cast(a, POINTER(c_int))
938 <ctypes.LP_c_long object at ...>
939 >>>
940
941 So, :func:`cast` can be used to assign to the ``values`` field of ``Bar`` the
942 structure::
943
944 >>> bar = Bar()
945 >>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
946 >>> print(bar.values[0])
947 0
948 >>>
949
950
951 .. _ctypes-incomplete-types:
952
953 Incomplete Types
954 ^^^^^^^^^^^^^^^^
955
956 *Incomplete Types* are structures, unions or arrays whose members are not yet
957 specified. In C, they are specified by forward declarations, which are defined
958 later::
959
960 struct cell; /* forward declaration */
961
962 struct cell {
963 char *name;
964 struct cell *next;
965 };
966
967 The straightforward translation into ctypes code would be this, but it does not
968 work::
969
970 >>> class cell(Structure):
971 ... _fields_ = [("name", c_char_p),
972 ... ("next", POINTER(cell))]
973 ...
974 Traceback (most recent call last):
975 File "<stdin>", line 1, in <module>
976 File "<stdin>", line 2, in cell
977 NameError: name 'cell' is not defined
978 >>>
979
980 because the new ``class cell`` is not available in the class statement itself.
981 In :mod:`ctypes`, we can define the ``cell`` class and set the
982 :attr:`~Structure._fields_` attribute later, after the class statement::
983
984 >>> from ctypes import *
985 >>> class cell(Structure):
986 ... pass
987 ...
988 >>> cell._fields_ = [("name", c_char_p),
989 ... ("next", POINTER(cell))]
990 >>>
991
992 Let's try it. We create two instances of ``cell``, and let them point to each
993 other, and finally follow the pointer chain a few times::
994
995 >>> c1 = cell()
996 >>> c1.name = b"foo"
997 >>> c2 = cell()
998 >>> c2.name = b"bar"
999 >>> c1.next = pointer(c2)
1000 >>> c2.next = pointer(c1)
1001 >>> p = c1
1002 >>> for i in range(8):
1003 ... print(p.name, end=" ")
1004 ... p = p.next[0]
1005 ...
1006 foo bar foo bar foo bar foo bar
1007 >>>
1008
1009
1010 .. _ctypes-callback-functions:
1011
1012 Callback functions
1013 ^^^^^^^^^^^^^^^^^^
1014
1015 :mod:`ctypes` allows creating C callable function pointers from Python callables.
1016 These are sometimes called *callback functions*.
1017
1018 First, you must create a class for the callback function. The class knows the
1019 calling convention, the return type, and the number and types of arguments this
1020 function will receive.
1021
1022 The :func:`CFUNCTYPE` factory function creates types for callback functions
1023 using the ``cdecl`` calling convention. On Windows, the :func:`WINFUNCTYPE`
1024 factory function creates types for callback functions using the ``stdcall``
1025 calling convention.
1026
1027 Both of these factory functions are called with the result type as first
1028 argument, and the callback functions expected argument types as the remaining
1029 arguments.
1030
1031 I will present an example here which uses the standard C library's
1032 :c:func:`!qsort` function, that is used to sort items with the help of a callback
1033 function. :c:func:`!qsort` will be used to sort an array of integers::
1034
1035 >>> IntArray5 = c_int * 5
1036 >>> ia = IntArray5(5, 1, 7, 33, 99)
1037 >>> qsort = libc.qsort
1038 >>> qsort.restype = None
1039 >>>
1040
1041 :func:`!qsort` must be called with a pointer to the data to sort, the number of
1042 items in the data array, the size of one item, and a pointer to the comparison
1043 function, the callback. The callback will then be called with two pointers to
1044 items, and it must return a negative integer if the first item is smaller than
1045 the second, a zero if they are equal, and a positive integer otherwise.
1046
1047 So our callback function receives pointers to integers, and must return an
1048 integer. First we create the ``type`` for the callback function::
1049
1050 >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
1051 >>>
1052
1053 To get started, here is a simple callback that shows the values it gets
1054 passed::
1055
1056 >>> def py_cmp_func(a, b):
1057 ... print("py_cmp_func", a[0], b[0])
1058 ... return 0
1059 ...
1060 >>> cmp_func = CMPFUNC(py_cmp_func)
1061 >>>
1062
1063 The result::
1064
1065 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX
1066 py_cmp_func 5 1
1067 py_cmp_func 33 99
1068 py_cmp_func 7 33
1069 py_cmp_func 5 7
1070 py_cmp_func 1 7
1071 >>>
1072
1073 Now we can actually compare the two items and return a useful result::
1074
1075 >>> def py_cmp_func(a, b):
1076 ... print("py_cmp_func", a[0], b[0])
1077 ... return a[0] - b[0]
1078 ...
1079 >>>
1080 >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX
1081 py_cmp_func 5 1
1082 py_cmp_func 33 99
1083 py_cmp_func 7 33
1084 py_cmp_func 1 7
1085 py_cmp_func 5 7
1086 >>>
1087
1088 As we can easily check, our array is sorted now::
1089
1090 >>> for i in ia: print(i, end=" ")
1091 ...
1092 1 5 7 33 99
1093 >>>
1094
1095 The function factories can be used as decorator factories, so we may as well
1096 write::
1097
1098 >>> @CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
1099 ... def py_cmp_func(a, b):
1100 ... print("py_cmp_func", a[0], b[0])
1101 ... return a[0] - b[0]
1102 ...
1103 >>> qsort(ia, len(ia), sizeof(c_int), py_cmp_func)
1104 py_cmp_func 5 1
1105 py_cmp_func 33 99
1106 py_cmp_func 7 33
1107 py_cmp_func 1 7
1108 py_cmp_func 5 7
1109 >>>
1110
1111 .. note::
1112
1113 Make sure you keep references to :func:`CFUNCTYPE` objects as long as they
1114 are used from C code. :mod:`ctypes` doesn't, and if you don't, they may be
1115 garbage collected, crashing your program when a callback is made.
1116
1117 Also, note that if the callback function is called in a thread created
1118 outside of Python's control (e.g. by the foreign code that calls the
1119 callback), ctypes creates a new dummy Python thread on every invocation. This
1120 behavior is correct for most purposes, but it means that values stored with
1121 :class:`threading.local` will *not* survive across different callbacks, even when
1122 those calls are made from the same C thread.
1123
1124 .. _ctypes-accessing-values-exported-from-dlls:
1125
1126 Accessing values exported from dlls
1127 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1128
1129 Some shared libraries not only export functions, they also export variables. An
1130 example in the Python library itself is the :c:data:`Py_Version`, Python
1131 runtime version number encoded in a single constant integer.
1132
1133 :mod:`ctypes` can access values like this with the :meth:`~_CData.in_dll` class methods of
1134 the type. *pythonapi* is a predefined symbol giving access to the Python C
1135 api::
1136
1137 >>> version = ctypes.c_int.in_dll(ctypes.pythonapi, "Py_Version")
1138 >>> print(hex(version.value))
1139 0x30c00a0
1140
1141 An extended example which also demonstrates the use of pointers accesses the
1142 :c:data:`PyImport_FrozenModules` pointer exported by Python.
1143
1144 Quoting the docs for that value:
1145
1146 This pointer is initialized to point to an array of :c:struct:`_frozen`
1147 records, terminated by one whose members are all ``NULL`` or zero. When a frozen
1148 module is imported, it is searched in this table. Third-party code could play
1149 tricks with this to provide a dynamically created collection of frozen modules.
1150
1151 So manipulating this pointer could even prove useful. To restrict the example
1152 size, we show only how this table can be read with :mod:`ctypes`::
1153
1154 >>> from ctypes import *
1155 >>>
1156 >>> class struct_frozen(Structure):
1157 ... _fields_ = [("name", c_char_p),
1158 ... ("code", POINTER(c_ubyte)),
1159 ... ("size", c_int),
1160 ... ("get_code", POINTER(c_ubyte)), # Function pointer
1161 ... ]
1162 ...
1163 >>>
1164
1165 We have defined the :c:struct:`_frozen` data type, so we can get the pointer
1166 to the table::
1167
1168 >>> FrozenTable = POINTER(struct_frozen)
1169 >>> table = FrozenTable.in_dll(pythonapi, "_PyImport_FrozenBootstrap")
1170 >>>
1171
1172 Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we
1173 can iterate over it, but we just have to make sure that our loop terminates,
1174 because pointers have no size. Sooner or later it would probably crash with an
1175 access violation or whatever, so it's better to break out of the loop when we
1176 hit the ``NULL`` entry::
1177
1178 >>> for item in table:
1179 ... if item.name is None:
1180 ... break
1181 ... print(item.name.decode("ascii"), item.size)
1182 ...
1183 _frozen_importlib 31764
1184 _frozen_importlib_external 41499
1185 zipimport 12345
1186 >>>
1187
1188 The fact that standard Python has a frozen module and a frozen package
1189 (indicated by the negative ``size`` member) is not well known, it is only used
1190 for testing. Try it out with ``import __hello__`` for example.
1191
1192
1193 .. _ctypes-surprises:
1194
1195 Surprises
1196 ^^^^^^^^^
1197
1198 There are some edges in :mod:`ctypes` where you might expect something other
1199 than what actually happens.
1200
1201 Consider the following example::
1202
1203 >>> from ctypes import *
1204 >>> class POINT(Structure):
1205 ... _fields_ = ("x", c_int), ("y", c_int)
1206 ...
1207 >>> class RECT(Structure):
1208 ... _fields_ = ("a", POINT), ("b", POINT)
1209 ...
1210 >>> p1 = POINT(1, 2)
1211 >>> p2 = POINT(3, 4)
1212 >>> rc = RECT(p1, p2)
1213 >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
1214 1 2 3 4
1215 >>> # now swap the two points
1216 >>> rc.a, rc.b = rc.b, rc.a
1217 >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
1218 3 4 3 4
1219 >>>
1220
1221 Hm. We certainly expected the last statement to print ``3 4 1 2``. What
1222 happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
1223
1224 >>> temp0, temp1 = rc.b, rc.a
1225 >>> rc.a = temp0
1226 >>> rc.b = temp1
1227 >>>
1228
1229 Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of
1230 the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer
1231 contents of ``temp0`` into ``rc`` 's buffer. This, in turn, changes the
1232 contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have
1233 the expected effect.
1234
1235 Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
1236 doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing
1237 the root-object's underlying buffer.
1238
1239 Another example that may behave differently from what one would expect is this::
1240
1241 >>> s = c_char_p()
1242 >>> s.value = b"abc def ghi"
1243 >>> s.value
1244 b'abc def ghi'
1245 >>> s.value is s.value
1246 False
1247 >>>
1248
1249 .. note::
1250
1251 Objects instantiated from :class:`c_char_p` can only have their value set to bytes
1252 or integers.
1253
1254 Why is it printing ``False``? ctypes instances are objects containing a memory
1255 block plus some :term:`descriptor`\s accessing the contents of the memory.
1256 Storing a Python object in the memory block does not store the object itself,
1257 instead the ``contents`` of the object is stored. Accessing the contents again
1258 constructs a new Python object each time!
1259
1260
1261 .. _ctypes-variable-sized-data-types:
1262
1263 Variable-sized data types
1264 ^^^^^^^^^^^^^^^^^^^^^^^^^
1265
1266 :mod:`ctypes` provides some support for variable-sized arrays and structures.
1267
1268 The :func:`resize` function can be used to resize the memory buffer of an
1269 existing ctypes object. The function takes the object as first argument, and
1270 the requested size in bytes as the second argument. The memory block cannot be
1271 made smaller than the natural memory block specified by the objects type, a
1272 :exc:`ValueError` is raised if this is tried::
1273
1274 >>> short_array = (c_short * 4)()
1275 >>> print(sizeof(short_array))
1276 8
1277 >>> resize(short_array, 4)
1278 Traceback (most recent call last):
1279 ...
1280 ValueError: minimum size is 8
1281 >>> resize(short_array, 32)
1282 >>> sizeof(short_array)
1283 32
1284 >>> sizeof(type(short_array))
1285 8
1286 >>>
1287
1288 This is nice and fine, but how would one access the additional elements
1289 contained in this array? Since the type still only knows about 4 elements, we
1290 get errors accessing other elements::
1291
1292 >>> short_array[:]
1293 [0, 0, 0, 0]
1294 >>> short_array[7]
1295 Traceback (most recent call last):
1296 ...
1297 IndexError: invalid index
1298 >>>
1299
1300 Another way to use variable-sized data types with :mod:`ctypes` is to use the
1301 dynamic nature of Python, and (re-)define the data type after the required size
1302 is already known, on a case by case basis.
1303
1304
1305 .. _ctypes-ctypes-reference:
1306
1307 ctypes reference
1308 ----------------
1309
1310
1311 .. _ctypes-finding-shared-libraries:
1312
1313 Finding shared libraries
1314 ^^^^^^^^^^^^^^^^^^^^^^^^
1315
1316 When programming in a compiled language, shared libraries are accessed when
1317 compiling/linking a program, and when the program is run.
1318
1319 The purpose of the :func:`~ctypes.util.find_library` function is to locate a library in a way
1320 similar to what the compiler or runtime loader does (on platforms with several
1321 versions of a shared library the most recent should be loaded), while the ctypes
1322 library loaders act like when a program is run, and call the runtime loader
1323 directly.
1324
1325 The :mod:`!ctypes.util` module provides a function which can help to determine
1326 the library to load.
1327
1328
1329 .. data:: find_library(name)
1330 :module: ctypes.util
1331 :noindex:
1332
1333 Try to find a library and return a pathname. *name* is the library name without
1334 any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this
1335 is the form used for the posix linker option :option:`!-l`). If no library can
1336 be found, returns ``None``.
1337
1338 The exact functionality is system dependent.
1339
1340 On Linux, :func:`~ctypes.util.find_library` tries to run external programs
1341 (``/sbin/ldconfig``, ``gcc``, ``objdump`` and ``ld``) to find the library file.
1342 It returns the filename of the library file.
1343
1344 Note that if the output of these programs does not correspond to the dynamic
1345 linker used by Python, the result of this function may be misleading.
1346
1347 .. versionchanged:: 3.6
1348 On Linux, the value of the environment variable ``LD_LIBRARY_PATH`` is used
1349 when searching for libraries, if a library cannot be found by any other means.
1350
1351 Here are some examples::
1352
1353 >>> from ctypes.util import find_library
1354 >>> find_library("m")
1355 'libm.so.6'
1356 >>> find_library("c")
1357 'libc.so.6'
1358 >>> find_library("bz2")
1359 'libbz2.so.1.0'
1360 >>>
1361
1362 On macOS and Android, :func:`~ctypes.util.find_library` uses the system's
1363 standard naming schemes and paths to locate the library, and returns a full
1364 pathname if successful::
1365
1366 >>> from ctypes.util import find_library
1367 >>> find_library("c")
1368 '/usr/lib/libc.dylib'
1369 >>> find_library("m")
1370 '/usr/lib/libm.dylib'
1371 >>> find_library("bz2")
1372 '/usr/lib/libbz2.dylib'
1373 >>> find_library("AGL")
1374 '/System/Library/Frameworks/AGL.framework/AGL'
1375 >>>
1376
1377 On Windows, :func:`~ctypes.util.find_library` searches along the system search path, and
1378 returns the full pathname, but since there is no predefined naming scheme a call
1379 like ``find_library("c")`` will fail and return ``None``.
1380
1381 If wrapping a shared library with :mod:`ctypes`, it *may* be better to determine
1382 the shared library name at development time, and hardcode that into the wrapper
1383 module instead of using :func:`~ctypes.util.find_library` to locate the library at runtime.
1384
1385
1386 .. _ctypes-loading-shared-libraries:
1387
1388 Loading shared libraries
1389 ^^^^^^^^^^^^^^^^^^^^^^^^
1390
1391 There are several ways to load shared libraries into the Python process. One
1392 way is to instantiate one of the following classes:
1393
1394
1395 .. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=None)
1396
1397 Instances of this class represent loaded shared libraries. Functions in these
1398 libraries use the standard C calling convention, and are assumed to return
1399 :c:expr:`int`.
1400
1401 On Windows creating a :class:`CDLL` instance may fail even if the DLL name
1402 exists. When a dependent DLL of the loaded DLL is not found, a
1403 :exc:`OSError` error is raised with the message *"[WinError 126] The
1404 specified module could not be found".* This error message does not contain
1405 the name of the missing DLL because the Windows API does not return this
1406 information making this error hard to diagnose. To resolve this error and
1407 determine which DLL is not found, you need to find the list of dependent
1408 DLLs and determine which one is not found using Windows debugging and
1409 tracing tools.
1410
1411 .. versionchanged:: 3.12
1412
1413 The *name* parameter can now be a :term:`path-like object`.
1414
1415 .. seealso::
1416
1417 `Microsoft DUMPBIN tool <https://docs.microsoft.com/cpp/build/reference/dependents>`_
1418 -- A tool to find DLL dependents.
1419
1420
1421 .. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=None)
1422
1423 Instances of this class represent loaded shared libraries,
1424 functions in these libraries use the ``stdcall`` calling convention, and are
1425 assumed to return the windows specific :class:`HRESULT` code. :class:`HRESULT`
1426 values contain information specifying whether the function call failed or
1427 succeeded, together with additional error code. If the return value signals a
1428 failure, an :class:`OSError` is automatically raised.
1429
1430 .. availability:: Windows
1431
1432 .. versionchanged:: 3.3
1433 :exc:`WindowsError` used to be raised,
1434 which is now an alias of :exc:`OSError`.
1435
1436 .. versionchanged:: 3.12
1437
1438 The *name* parameter can now be a :term:`path-like object`.
1439
1440
1441 .. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=None)
1442
1443 Instances of this class represent loaded shared libraries,
1444 functions in these libraries use the ``stdcall`` calling convention, and are
1445 assumed to return :c:expr:`int` by default.
1446
1447 .. availability:: Windows
1448
1449 .. versionchanged:: 3.12
1450
1451 The *name* parameter can now be a :term:`path-like object`.
1452
1453
1454 The Python :term:`global interpreter lock` is released before calling any
1455 function exported by these libraries, and reacquired afterwards.
1456
1457
1458 .. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)
1459
1460 Instances of this class behave like :class:`CDLL` instances, except that the
1461 Python GIL is *not* released during the function call, and after the function
1462 execution the Python error flag is checked. If the error flag is set, a Python
1463 exception is raised.
1464
1465 Thus, this is only useful to call Python C api functions directly.
1466
1467 .. versionchanged:: 3.12
1468
1469 The *name* parameter can now be a :term:`path-like object`.
1470
1471 All these classes can be instantiated by calling them with at least one
1472 argument, the pathname of the shared library. If you have an existing handle to
1473 an already loaded shared library, it can be passed as the ``handle`` named
1474 parameter, otherwise the underlying platform's :c:func:`!dlopen` or
1475 :c:func:`!LoadLibrary` function is used to load the library into
1476 the process, and to get a handle to it.
1477
1478 The *mode* parameter can be used to specify how the library is loaded. For
1479 details, consult the :manpage:`dlopen(3)` manpage. On Windows, *mode* is
1480 ignored. On posix systems, RTLD_NOW is always added, and is not
1481 configurable.
1482
1483 The *use_errno* parameter, when set to true, enables a ctypes mechanism that
1484 allows accessing the system :data:`errno` error number in a safe way.
1485 :mod:`ctypes` maintains a thread-local copy of the system's :data:`errno`
1486 variable; if you call foreign functions created with ``use_errno=True`` then the
1487 :data:`errno` value before the function call is swapped with the ctypes private
1488 copy, the same happens immediately after the function call.
1489
1490 The function :func:`ctypes.get_errno` returns the value of the ctypes private
1491 copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy
1492 to a new value and returns the former value.
1493
1494 The *use_last_error* parameter, when set to true, enables the same mechanism for
1495 the Windows error code which is managed by the :func:`GetLastError` and
1496 :func:`!SetLastError` Windows API functions; :func:`ctypes.get_last_error` and
1497 :func:`ctypes.set_last_error` are used to request and change the ctypes private
1498 copy of the windows error code.
1499
1500 The *winmode* parameter is used on Windows to specify how the library is loaded
1501 (since *mode* is ignored). It takes any value that is valid for the Win32 API
1502 ``LoadLibraryEx`` flags parameter. When omitted, the default is to use the
1503 flags that result in the most secure DLL load, which avoids issues such as DLL
1504 hijacking. Passing the full path to the DLL is the safest way to ensure the
1505 correct library and dependencies are loaded.
1506
1507 .. versionchanged:: 3.8
1508 Added *winmode* parameter.
1509
1510
1511 .. data:: RTLD_GLOBAL
1512 :noindex:
1513
1514 Flag to use as *mode* parameter. On platforms where this flag is not available,
1515 it is defined as the integer zero.
1516
1517
1518 .. data:: RTLD_LOCAL
1519 :noindex:
1520
1521 Flag to use as *mode* parameter. On platforms where this is not available, it
1522 is the same as *RTLD_GLOBAL*.
1523
1524
1525 .. data:: DEFAULT_MODE
1526 :noindex:
1527
1528 The default mode which is used to load shared libraries. On OSX 10.3, this is
1529 *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*.
1530
1531 Instances of these classes have no public methods. Functions exported by the
1532 shared library can be accessed as attributes or by index. Please note that
1533 accessing the function through an attribute caches the result and therefore
1534 accessing it repeatedly returns the same object each time. On the other hand,
1535 accessing it through an index returns a new object each time::
1536
1537 >>> from ctypes import CDLL
1538 >>> libc = CDLL("libc.so.6") # On Linux
1539 >>> libc.time == libc.time
1540 True
1541 >>> libc['time'] == libc['time']
1542 False
1543
1544 The following public attributes are available, their name starts with an
1545 underscore to not clash with exported function names:
1546
1547
1548 .. attribute:: PyDLL._handle
1549
1550 The system handle used to access the library.
1551
1552
1553 .. attribute:: PyDLL._name
1554
1555 The name of the library passed in the constructor.
1556
1557 Shared libraries can also be loaded by using one of the prefabricated objects,
1558 which are instances of the :class:`LibraryLoader` class, either by calling the
1559 :meth:`~LibraryLoader.LoadLibrary` method, or by retrieving the library as
1560 attribute of the loader instance.
1561
1562
1563 .. class:: LibraryLoader(dlltype)
1564
1565 Class which loads shared libraries. *dlltype* should be one of the
1566 :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types.
1567
1568 :meth:`!__getattr__` has special behavior: It allows loading a shared library by
1569 accessing it as attribute of a library loader instance. The result is cached,
1570 so repeated attribute accesses return the same library each time.
1571
1572 .. method:: LoadLibrary(name)
1573
1574 Load a shared library into the process and return it. This method always
1575 returns a new instance of the library.
1576
1577
1578 These prefabricated library loaders are available:
1579
1580 .. data:: cdll
1581 :noindex:
1582
1583 Creates :class:`CDLL` instances.
1584
1585
1586 .. data:: windll
1587 :noindex:
1588
1589 Creates :class:`WinDLL` instances.
1590
1591 .. availability:: Windows
1592
1593
1594 .. data:: oledll
1595 :noindex:
1596
1597 Creates :class:`OleDLL` instances.
1598
1599 .. availability:: Windows
1600
1601
1602 .. data:: pydll
1603 :noindex:
1604
1605 Creates :class:`PyDLL` instances.
1606
1607
1608 For accessing the C Python api directly, a ready-to-use Python shared library
1609 object is available:
1610
1611 .. data:: pythonapi
1612 :noindex:
1613
1614 An instance of :class:`PyDLL` that exposes Python C API functions as
1615 attributes. Note that all these functions are assumed to return C
1616 :c:expr:`int`, which is of course not always the truth, so you have to assign
1617 the correct :attr:`!restype` attribute to use these functions.
1618
1619 .. audit-event:: ctypes.dlopen name ctypes.LibraryLoader
1620
1621 Loading a library through any of these objects raises an
1622 :ref:`auditing event <auditing>` ``ctypes.dlopen`` with string argument
1623 ``name``, the name used to load the library.
1624
1625 .. audit-event:: ctypes.dlsym library,name ctypes.LibraryLoader
1626
1627 Accessing a function on a loaded library raises an auditing event
1628 ``ctypes.dlsym`` with arguments ``library`` (the library object) and ``name``
1629 (the symbol's name as a string or integer).
1630
1631 .. audit-event:: ctypes.dlsym/handle handle,name ctypes.LibraryLoader
1632
1633 In cases when only the library handle is available rather than the object,
1634 accessing a function raises an auditing event ``ctypes.dlsym/handle`` with
1635 arguments ``handle`` (the raw library handle) and ``name``.
1636
1637 .. _ctypes-foreign-functions:
1638
1639 Foreign functions
1640 ^^^^^^^^^^^^^^^^^
1641
1642 As explained in the previous section, foreign functions can be accessed as
1643 attributes of loaded shared libraries. The function objects created in this way
1644 by default accept any number of arguments, accept any ctypes data instances as
1645 arguments, and return the default result type specified by the library loader.
1646
1647 They are instances of a private local class :class:`!_FuncPtr` (not exposed
1648 in :mod:`!ctypes`) which inherits from the private :class:`_CFuncPtr` class:
1649
1650 .. doctest::
1651
1652 >>> import ctypes
1653 >>> lib = ctypes.CDLL(None)
1654 >>> issubclass(lib._FuncPtr, ctypes._CFuncPtr)
1655 True
1656 >>> lib._FuncPtr is ctypes._CFuncPtr
1657 False
1658
1659 .. class:: _CFuncPtr
1660
1661 Base class for C callable foreign functions.
1662
1663 Instances of foreign functions are also C compatible data types; they
1664 represent C function pointers.
1665
1666 This behavior can be customized by assigning to special attributes of the
1667 foreign function object.
1668
1669 .. attribute:: restype
1670
1671 Assign a ctypes type to specify the result type of the foreign function.
1672 Use ``None`` for :c:expr:`void`, a function not returning anything.
1673
1674 It is possible to assign a callable Python object that is not a ctypes
1675 type, in this case the function is assumed to return a C :c:expr:`int`, and
1676 the callable will be called with this integer, allowing further
1677 processing or error checking. Using this is deprecated, for more flexible
1678 post processing or error checking use a ctypes data type as
1679 :attr:`!restype` and assign a callable to the :attr:`errcheck` attribute.
1680
1681 .. attribute:: argtypes
1682
1683 Assign a tuple of ctypes types to specify the argument types that the
1684 function accepts. Functions using the ``stdcall`` calling convention can
1685 only be called with the same number of arguments as the length of this
1686 tuple; functions using the C calling convention accept additional,
1687 unspecified arguments as well.
1688
1689 When a foreign function is called, each actual argument is passed to the
1690 :meth:`~_CData.from_param` class method of the items in the :attr:`argtypes`
1691 tuple, this method allows adapting the actual argument to an object that
1692 the foreign function accepts. For example, a :class:`c_char_p` item in
1693 the :attr:`argtypes` tuple will convert a string passed as argument into
1694 a bytes object using ctypes conversion rules.
1695
1696 New: It is now possible to put items in argtypes which are not ctypes
1697 types, but each item must have a :meth:`~_CData.from_param` method which returns a
1698 value usable as argument (integer, string, ctypes instance). This allows
1699 defining adapters that can adapt custom objects as function parameters.
1700
1701 .. attribute:: errcheck
1702
1703 Assign a Python function or another callable to this attribute. The
1704 callable will be called with three or more arguments:
1705
1706 .. function:: callable(result, func, arguments)
1707 :noindex:
1708 :module:
1709
1710 *result* is what the foreign function returns, as specified by the
1711 :attr:`!restype` attribute.
1712
1713 *func* is the foreign function object itself, this allows reusing the
1714 same callable object to check or post process the results of several
1715 functions.
1716
1717 *arguments* is a tuple containing the parameters originally passed to
1718 the function call, this allows specializing the behavior on the
1719 arguments used.
1720
1721 The object that this function returns will be returned from the
1722 foreign function call, but it can also check the result value
1723 and raise an exception if the foreign function call failed.
1724
1725
1726 .. exception:: ArgumentError
1727
1728 This exception is raised when a foreign function call cannot convert one of the
1729 passed arguments.
1730
1731
1732 .. audit-event:: ctypes.set_exception code foreign-functions
1733
1734 On Windows, when a foreign function call raises a system exception (for
1735 example, due to an access violation), it will be captured and replaced with
1736 a suitable Python exception. Further, an auditing event
1737 ``ctypes.set_exception`` with argument ``code`` will be raised, allowing an
1738 audit hook to replace the exception with its own.
1739
1740 .. audit-event:: ctypes.call_function func_pointer,arguments foreign-functions
1741
1742 Some ways to invoke foreign function calls may raise an auditing event
1743 ``ctypes.call_function`` with arguments ``function pointer`` and ``arguments``.
1744
1745 .. _ctypes-function-prototypes:
1746
1747 Function prototypes
1748 ^^^^^^^^^^^^^^^^^^^
1749
1750 Foreign functions can also be created by instantiating function prototypes.
1751 Function prototypes are similar to function prototypes in C; they describe a
1752 function (return type, argument types, calling convention) without defining an
1753 implementation. The factory functions must be called with the desired result
1754 type and the argument types of the function, and can be used as decorator
1755 factories, and as such, be applied to functions through the ``@wrapper`` syntax.
1756 See :ref:`ctypes-callback-functions` for examples.
1757
1758
1759 .. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
1760
1761 The returned function prototype creates functions that use the standard C
1762 calling convention. The function will release the GIL during the call. If
1763 *use_errno* is set to true, the ctypes private copy of the system
1764 :data:`errno` variable is exchanged with the real :data:`errno` value before
1765 and after the call; *use_last_error* does the same for the Windows error
1766 code.
1767
1768
1769 .. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
1770
1771 The returned function prototype creates functions that use the
1772 ``stdcall`` calling convention. The function will
1773 release the GIL during the call. *use_errno* and *use_last_error* have the
1774 same meaning as above.
1775
1776 .. availability:: Windows
1777
1778
1779 .. function:: PYFUNCTYPE(restype, *argtypes)
1780
1781 The returned function prototype creates functions that use the Python calling
1782 convention. The function will *not* release the GIL during the call.
1783
1784 Function prototypes created by these factory functions can be instantiated in
1785 different ways, depending on the type and number of the parameters in the call:
1786
1787 .. function:: prototype(address)
1788 :noindex:
1789 :module:
1790
1791 Returns a foreign function at the specified address which must be an integer.
1792
1793
1794 .. function:: prototype(callable)
1795 :noindex:
1796 :module:
1797
1798 Create a C callable function (a callback function) from a Python *callable*.
1799
1800
1801 .. function:: prototype(func_spec[, paramflags])
1802 :noindex:
1803 :module:
1804
1805 Returns a foreign function exported by a shared library. *func_spec* must
1806 be a 2-tuple ``(name_or_ordinal, library)``. The first item is the name of
1807 the exported function as string, or the ordinal of the exported function
1808 as small integer. The second item is the shared library instance.
1809
1810
1811 .. function:: prototype(vtbl_index, name[, paramflags[, iid]])
1812 :noindex:
1813 :module:
1814
1815 Returns a foreign function that will call a COM method. *vtbl_index* is
1816 the index into the virtual function table, a small non-negative
1817 integer. *name* is name of the COM method. *iid* is an optional pointer to
1818 the interface identifier which is used in extended error reporting.
1819
1820 COM methods use a special calling convention: They require a pointer to
1821 the COM interface as first argument, in addition to those parameters that
1822 are specified in the :attr:`!argtypes` tuple.
1823
1824 The optional *paramflags* parameter creates foreign function wrappers with much
1825 more functionality than the features described above.
1826
1827 *paramflags* must be a tuple of the same length as :attr:`~_CFuncPtr.argtypes`.
1828
1829 Each item in this tuple contains further information about a parameter, it must
1830 be a tuple containing one, two, or three items.
1831
1832 The first item is an integer containing a combination of direction
1833 flags for the parameter:
1834
1835 1
1836 Specifies an input parameter to the function.
1837
1838 2
1839 Output parameter. The foreign function fills in a value.
1840
1841 4
1842 Input parameter which defaults to the integer zero.
1843
1844 The optional second item is the parameter name as string. If this is specified,
1845 the foreign function can be called with named parameters.
1846
1847 The optional third item is the default value for this parameter.
1848
1849
1850 The following example demonstrates how to wrap the Windows ``MessageBoxW`` function so
1851 that it supports default parameters and named arguments. The C declaration from
1852 the windows header file is this::
1853
1854 WINUSERAPI int WINAPI
1855 MessageBoxW(
1856 HWND hWnd,
1857 LPCWSTR lpText,
1858 LPCWSTR lpCaption,
1859 UINT uType);
1860
1861 Here is the wrapping with :mod:`ctypes`::
1862
1863 >>> from ctypes import c_int, WINFUNCTYPE, windll
1864 >>> from ctypes.wintypes import HWND, LPCWSTR, UINT
1865 >>> prototype = WINFUNCTYPE(c_int, HWND, LPCWSTR, LPCWSTR, UINT)
1866 >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", "Hello from ctypes"), (1, "flags", 0)
1867 >>> MessageBox = prototype(("MessageBoxW", windll.user32), paramflags)
1868
1869 The ``MessageBox`` foreign function can now be called in these ways::
1870
1871 >>> MessageBox()
1872 >>> MessageBox(text="Spam, spam, spam")
1873 >>> MessageBox(flags=2, text="foo bar")
1874
1875 A second example demonstrates output parameters. The win32 ``GetWindowRect``
1876 function retrieves the dimensions of a specified window by copying them into
1877 ``RECT`` structure that the caller has to supply. Here is the C declaration::
1878
1879 WINUSERAPI BOOL WINAPI
1880 GetWindowRect(
1881 HWND hWnd,
1882 LPRECT lpRect);
1883
1884 Here is the wrapping with :mod:`ctypes`::
1885
1886 >>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
1887 >>> from ctypes.wintypes import BOOL, HWND, RECT
1888 >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
1889 >>> paramflags = (1, "hwnd"), (2, "lprect")
1890 >>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
1891 >>>
1892
1893 Functions with output parameters will automatically return the output parameter
1894 value if there is a single one, or a tuple containing the output parameter
1895 values when there are more than one, so the GetWindowRect function now returns a
1896 RECT instance, when called.
1897
1898 Output parameters can be combined with the :attr:`~_CFuncPtr.errcheck` protocol to do
1899 further output processing and error checking. The win32 ``GetWindowRect`` api
1900 function returns a ``BOOL`` to signal success or failure, so this function could
1901 do the error checking, and raises an exception when the api call failed::
1902
1903 >>> def errcheck(result, func, args):
1904 ... if not result:
1905 ... raise WinError()
1906 ... return args
1907 ...
1908 >>> GetWindowRect.errcheck = errcheck
1909 >>>
1910
1911 If the :attr:`~_CFuncPtr.errcheck` function returns the argument tuple it receives
1912 unchanged, :mod:`ctypes` continues the normal processing it does on the output
1913 parameters. If you want to return a tuple of window coordinates instead of a
1914 ``RECT`` instance, you can retrieve the fields in the function and return them
1915 instead, the normal processing will no longer take place::
1916
1917 >>> def errcheck(result, func, args):
1918 ... if not result:
1919 ... raise WinError()
1920 ... rc = args[1]
1921 ... return rc.left, rc.top, rc.bottom, rc.right
1922 ...
1923 >>> GetWindowRect.errcheck = errcheck
1924 >>>
1925
1926
1927 .. _ctypes-utility-functions:
1928
1929 Utility functions
1930 ^^^^^^^^^^^^^^^^^
1931
1932 .. function:: addressof(obj)
1933
1934 Returns the address of the memory buffer as integer. *obj* must be an
1935 instance of a ctypes type.
1936
1937 .. audit-event:: ctypes.addressof obj ctypes.addressof
1938
1939
1940 .. function:: alignment(obj_or_type)
1941
1942 Returns the alignment requirements of a ctypes type. *obj_or_type* must be a
1943 ctypes type or instance.
1944
1945
1946 .. function:: byref(obj[, offset])
1947
1948 Returns a light-weight pointer to *obj*, which must be an instance of a
1949 ctypes type. *offset* defaults to zero, and must be an integer that will be
1950 added to the internal pointer value.
1951
1952 ``byref(obj, offset)`` corresponds to this C code::
1953
1954 (((char *)&obj) + offset)
1955
1956 The returned object can only be used as a foreign function call parameter.
1957 It behaves similar to ``pointer(obj)``, but the construction is a lot faster.
1958
1959
1960 .. function:: cast(obj, type)
1961
1962 This function is similar to the cast operator in C. It returns a new instance
1963 of *type* which points to the same memory block as *obj*. *type* must be a
1964 pointer type, and *obj* must be an object that can be interpreted as a
1965 pointer.
1966
1967
1968 .. function:: create_string_buffer(init, size=None)
1969 create_string_buffer(size)
1970
1971 This function creates a mutable character buffer. The returned object is a
1972 ctypes array of :class:`c_char`.
1973
1974 If *size* is given (and not ``None``), it must be an :class:`int`.
1975 It specifies the size of the returned array.
1976
1977 If the *init* argument is given, it must be :class:`bytes`. It is used
1978 to initialize the array items. Bytes not initialized this way are
1979 set to zero (NUL).
1980
1981 If *size* is not given (or if it is ``None``), the buffer is made one element
1982 larger than *init*, effectively adding a NUL terminator.
1983
1984 If both arguments are given, *size* must not be less than ``len(init)``.
1985
1986 .. warning::
1987
1988 If *size* is equal to ``len(init)``, a NUL terminator is
1989 not added. Do not treat such a buffer as a C string.
1990
1991 For example::
1992
1993 >>> bytes(create_string_buffer(2))
1994 b'\x00\x00'
1995 >>> bytes(create_string_buffer(b'ab'))
1996 b'ab\x00'
1997 >>> bytes(create_string_buffer(b'ab', 2))
1998 b'ab'
1999 >>> bytes(create_string_buffer(b'ab', 4))
2000 b'ab\x00\x00'
2001 >>> bytes(create_string_buffer(b'abcdef', 2))
2002 Traceback (most recent call last):
2003 ...
2004 ValueError: byte string too long
2005
2006 .. audit-event:: ctypes.create_string_buffer init,size ctypes.create_string_buffer
2007
2008
2009 .. function:: create_unicode_buffer(init, size=None)
2010 create_unicode_buffer(size)
2011
2012 This function creates a mutable unicode character buffer. The returned object is
2013 a ctypes array of :class:`c_wchar`.
2014
2015 The function takes the same arguments as :func:`~create_string_buffer` except
2016 *init* must be a string and *size* counts :class:`c_wchar`.
2017
2018 .. audit-event:: ctypes.create_unicode_buffer init,size ctypes.create_unicode_buffer
2019
2020
2021 .. function:: DllCanUnloadNow()
2022
2023 This function is a hook which allows implementing in-process
2024 COM servers with ctypes. It is called from the DllCanUnloadNow function that
2025 the _ctypes extension dll exports.
2026
2027 .. availability:: Windows
2028
2029
2030 .. function:: DllGetClassObject()
2031
2032 This function is a hook which allows implementing in-process
2033 COM servers with ctypes. It is called from the DllGetClassObject function
2034 that the ``_ctypes`` extension dll exports.
2035
2036 .. availability:: Windows
2037
2038
2039 .. function:: find_library(name)
2040 :module: ctypes.util
2041
2042 Try to find a library and return a pathname. *name* is the library name
2043 without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version
2044 number (this is the form used for the posix linker option :option:`!-l`). If
2045 no library can be found, returns ``None``.
2046
2047 The exact functionality is system dependent.
2048
2049 See :ref:`ctypes-finding-shared-libraries` for complete documentation.
2050
2051
2052 .. function:: find_msvcrt()
2053 :module: ctypes.util
2054
2055 Returns the filename of the VC runtime library used by Python,
2056 and by the extension modules. If the name of the library cannot be
2057 determined, ``None`` is returned.
2058
2059 If you need to free memory, for example, allocated by an extension module
2060 with a call to the ``free(void *)``, it is important that you use the
2061 function in the same library that allocated the memory.
2062
2063 .. availability:: Windows
2064
2065
2066 .. function:: FormatError([code])
2067
2068 Returns a textual description of the error code *code*. If no
2069 error code is specified, the last error code is used by calling the Windows
2070 api function GetLastError.
2071
2072 .. availability:: Windows
2073
2074
2075 .. function:: GetLastError()
2076
2077 Returns the last error code set by Windows in the calling thread.
2078 This function calls the Windows ``GetLastError()`` function directly,
2079 it does not return the ctypes-private copy of the error code.
2080
2081 .. availability:: Windows
2082
2083
2084 .. function:: get_errno()
2085
2086 Returns the current value of the ctypes-private copy of the system
2087 :data:`errno` variable in the calling thread.
2088
2089 .. audit-event:: ctypes.get_errno "" ctypes.get_errno
2090
2091 .. function:: get_last_error()
2092
2093 Returns the current value of the ctypes-private copy of the system
2094 :data:`!LastError` variable in the calling thread.
2095
2096 .. availability:: Windows
2097
2098 .. audit-event:: ctypes.get_last_error "" ctypes.get_last_error
2099
2100
2101 .. function:: memmove(dst, src, count)
2102
2103 Same as the standard C memmove library function: copies *count* bytes from
2104 *src* to *dst*. *dst* and *src* must be integers or ctypes instances that can
2105 be converted to pointers.
2106
2107
2108 .. function:: memset(dst, c, count)
2109
2110 Same as the standard C memset library function: fills the memory block at
2111 address *dst* with *count* bytes of value *c*. *dst* must be an integer
2112 specifying an address, or a ctypes instance.
2113
2114
2115 .. function:: POINTER(type, /)
2116
2117 Create and return a new ctypes pointer type. Pointer types are cached and
2118 reused internally, so calling this function repeatedly is cheap.
2119 *type* must be a ctypes type.
2120
2121
2122 .. function:: pointer(obj, /)
2123
2124 Create a new pointer instance, pointing to *obj*.
2125 The returned object is of the type ``POINTER(type(obj))``.
2126
2127 Note: If you just want to pass a pointer to an object to a foreign function
2128 call, you should use ``byref(obj)`` which is much faster.
2129
2130
2131 .. function:: resize(obj, size)
2132
2133 This function resizes the internal memory buffer of *obj*, which must be an
2134 instance of a ctypes type. It is not possible to make the buffer smaller
2135 than the native size of the objects type, as given by ``sizeof(type(obj))``,
2136 but it is possible to enlarge the buffer.
2137
2138
2139 .. function:: set_errno(value)
2140
2141 Set the current value of the ctypes-private copy of the system :data:`errno`
2142 variable in the calling thread to *value* and return the previous value.
2143
2144 .. audit-event:: ctypes.set_errno errno ctypes.set_errno
2145
2146
2147 .. function:: set_last_error(value)
2148
2149 Sets the current value of the ctypes-private copy of the system
2150 :data:`!LastError` variable in the calling thread to *value* and return the
2151 previous value.
2152
2153 .. availability:: Windows
2154
2155 .. audit-event:: ctypes.set_last_error error ctypes.set_last_error
2156
2157
2158 .. function:: sizeof(obj_or_type)
2159
2160 Returns the size in bytes of a ctypes type or instance memory buffer.
2161 Does the same as the C ``sizeof`` operator.
2162
2163
2164 .. function:: string_at(ptr, size=-1)
2165
2166 Return the byte string at *void \*ptr*.
2167 If *size* is specified, it is used as size, otherwise the string is assumed
2168 to be zero-terminated.
2169
2170 .. audit-event:: ctypes.string_at ptr,size ctypes.string_at
2171
2172
2173 .. function:: WinError(code=None, descr=None)
2174
2175 This function is probably the worst-named thing in ctypes. It
2176 creates an instance of :exc:`OSError`. If *code* is not specified,
2177 ``GetLastError`` is called to determine the error code. If *descr* is not
2178 specified, :func:`FormatError` is called to get a textual description of the
2179 error.
2180
2181 .. availability:: Windows
2182
2183 .. versionchanged:: 3.3
2184 An instance of :exc:`WindowsError` used to be created, which is now an
2185 alias of :exc:`OSError`.
2186
2187
2188 .. function:: wstring_at(ptr, size=-1)
2189
2190 Return the wide-character string at *void \*ptr*.
2191 If *size* is specified, it is used as the number of
2192 characters of the string, otherwise the string is assumed to be
2193 zero-terminated.
2194
2195 .. audit-event:: ctypes.wstring_at ptr,size ctypes.wstring_at
2196
2197
2198 .. _ctypes-data-types:
2199
2200 Data types
2201 ^^^^^^^^^^
2202
2203
2204 .. class:: _CData
2205
2206 This non-public class is the common base class of all ctypes data types.
2207 Among other things, all ctypes type instances contain a memory block that
2208 hold C compatible data; the address of the memory block is returned by the
2209 :func:`addressof` helper function. Another instance variable is exposed as
2210 :attr:`_objects`; this contains other Python objects that need to be kept
2211 alive in case the memory block contains pointers.
2212
2213 Common methods of ctypes data types, these are all class methods (to be
2214 exact, they are methods of the :term:`metaclass`):
2215
2216 .. method:: _CData.from_buffer(source[, offset])
2217
2218 This method returns a ctypes instance that shares the buffer of the
2219 *source* object. The *source* object must support the writeable buffer
2220 interface. The optional *offset* parameter specifies an offset into the
2221 source buffer in bytes; the default is zero. If the source buffer is not
2222 large enough a :exc:`ValueError` is raised.
2223
2224 .. audit-event:: ctypes.cdata/buffer pointer,size,offset ctypes._CData.from_buffer
2225
2226 .. method:: _CData.from_buffer_copy(source[, offset])
2227
2228 This method creates a ctypes instance, copying the buffer from the
2229 *source* object buffer which must be readable. The optional *offset*
2230 parameter specifies an offset into the source buffer in bytes; the default
2231 is zero. If the source buffer is not large enough a :exc:`ValueError` is
2232 raised.
2233
2234 .. audit-event:: ctypes.cdata/buffer pointer,size,offset ctypes._CData.from_buffer_copy
2235
2236 .. method:: from_address(address)
2237
2238 This method returns a ctypes type instance using the memory specified by
2239 *address* which must be an integer.
2240
2241 .. audit-event:: ctypes.cdata address ctypes._CData.from_address
2242
2243 This method, and others that indirectly call this method, raises an
2244 :ref:`auditing event <auditing>` ``ctypes.cdata`` with argument
2245 ``address``.
2246
2247 .. method:: from_param(obj)
2248
2249 This method adapts *obj* to a ctypes type. It is called with the actual
2250 object used in a foreign function call when the type is present in the
2251 foreign function's :attr:`~_CFuncPtr.argtypes` tuple;
2252 it must return an object that can be used as a function call parameter.
2253
2254 All ctypes data types have a default implementation of this classmethod
2255 that normally returns *obj* if that is an instance of the type. Some
2256 types accept other objects as well.
2257
2258 .. method:: in_dll(library, name)
2259
2260 This method returns a ctypes type instance exported by a shared
2261 library. *name* is the name of the symbol that exports the data, *library*
2262 is the loaded shared library.
2263
2264 Common instance variables of ctypes data types:
2265
2266 .. attribute:: _b_base_
2267
2268 Sometimes ctypes data instances do not own the memory block they contain,
2269 instead they share part of the memory block of a base object. The
2270 :attr:`_b_base_` read-only member is the root ctypes object that owns the
2271 memory block.
2272
2273 .. attribute:: _b_needsfree_
2274
2275 This read-only variable is true when the ctypes data instance has
2276 allocated the memory block itself, false otherwise.
2277
2278 .. attribute:: _objects
2279
2280 This member is either ``None`` or a dictionary containing Python objects
2281 that need to be kept alive so that the memory block contents is kept
2282 valid. This object is only exposed for debugging; never modify the
2283 contents of this dictionary.
2284
2285
2286 .. _ctypes-fundamental-data-types-2:
2287
2288 Fundamental data types
2289 ^^^^^^^^^^^^^^^^^^^^^^
2290
2291 .. class:: _SimpleCData
2292
2293 This non-public class is the base class of all fundamental ctypes data
2294 types. It is mentioned here because it contains the common attributes of the
2295 fundamental ctypes data types. :class:`_SimpleCData` is a subclass of
2296 :class:`_CData`, so it inherits their methods and attributes. ctypes data
2297 types that are not and do not contain pointers can now be pickled.
2298
2299 Instances have a single attribute:
2300
2301 .. attribute:: value
2302
2303 This attribute contains the actual value of the instance. For integer and
2304 pointer types, it is an integer, for character types, it is a single
2305 character bytes object or string, for character pointer types it is a
2306 Python bytes object or string.
2307
2308 When the ``value`` attribute is retrieved from a ctypes instance, usually
2309 a new object is returned each time. :mod:`ctypes` does *not* implement
2310 original object return, always a new object is constructed. The same is
2311 true for all other ctypes object instances.
2312
2313
2314 Fundamental data types, when returned as foreign function call results, or, for
2315 example, by retrieving structure field members or array items, are transparently
2316 converted to native Python types. In other words, if a foreign function has a
2317 :attr:`~_CFuncPtr.restype` of :class:`c_char_p`, you will always receive a Python bytes
2318 object, *not* a :class:`c_char_p` instance.
2319
2320 .. XXX above is false, it actually returns a Unicode string
2321
2322 Subclasses of fundamental data types do *not* inherit this behavior. So, if a
2323 foreign functions :attr:`!restype` is a subclass of :class:`c_void_p`, you will
2324 receive an instance of this subclass from the function call. Of course, you can
2325 get the value of the pointer by accessing the ``value`` attribute.
2326
2327 These are the fundamental ctypes data types:
2328
2329 .. class:: c_byte
2330
2331 Represents the C :c:expr:`signed char` datatype, and interprets the value as
2332 small integer. The constructor accepts an optional integer initializer; no
2333 overflow checking is done.
2334
2335
2336 .. class:: c_char
2337
2338 Represents the C :c:expr:`char` datatype, and interprets the value as a single
2339 character. The constructor accepts an optional string initializer, the
2340 length of the string must be exactly one character.
2341
2342
2343 .. class:: c_char_p
2344
2345 Represents the C :c:expr:`char *` datatype when it points to a zero-terminated
2346 string. For a general character pointer that may also point to binary data,
2347 ``POINTER(c_char)`` must be used. The constructor accepts an integer
2348 address, or a bytes object.
2349
2350
2351 .. class:: c_double
2352
2353 Represents the C :c:expr:`double` datatype. The constructor accepts an
2354 optional float initializer.
2355
2356
2357 .. class:: c_longdouble
2358
2359 Represents the C :c:expr:`long double` datatype. The constructor accepts an
2360 optional float initializer. On platforms where ``sizeof(long double) ==
2361 sizeof(double)`` it is an alias to :class:`c_double`.
2362
2363 .. class:: c_float
2364
2365 Represents the C :c:expr:`float` datatype. The constructor accepts an
2366 optional float initializer.
2367
2368
2369 .. class:: c_int
2370
2371 Represents the C :c:expr:`signed int` datatype. The constructor accepts an
2372 optional integer initializer; no overflow checking is done. On platforms
2373 where ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`.
2374
2375
2376 .. class:: c_int8
2377
2378 Represents the C 8-bit :c:expr:`signed int` datatype. It is an alias for
2379 :class:`c_byte`.
2380
2381
2382 .. class:: c_int16
2383
2384 Represents the C 16-bit :c:expr:`signed int` datatype. Usually an alias for
2385 :class:`c_short`.
2386
2387
2388 .. class:: c_int32
2389
2390 Represents the C 32-bit :c:expr:`signed int` datatype. Usually an alias for
2391 :class:`c_int`.
2392
2393
2394 .. class:: c_int64
2395
2396 Represents the C 64-bit :c:expr:`signed int` datatype. Usually an alias for
2397 :class:`c_longlong`.
2398
2399
2400 .. class:: c_long
2401
2402 Represents the C :c:expr:`signed long` datatype. The constructor accepts an
2403 optional integer initializer; no overflow checking is done.
2404
2405
2406 .. class:: c_longlong
2407
2408 Represents the C :c:expr:`signed long long` datatype. The constructor accepts
2409 an optional integer initializer; no overflow checking is done.
2410
2411
2412 .. class:: c_short
2413
2414 Represents the C :c:expr:`signed short` datatype. The constructor accepts an
2415 optional integer initializer; no overflow checking is done.
2416
2417
2418 .. class:: c_size_t
2419
2420 Represents the C :c:type:`size_t` datatype.
2421
2422
2423 .. class:: c_ssize_t
2424
2425 Represents the C :c:type:`ssize_t` datatype.
2426
2427 .. versionadded:: 3.2
2428
2429
2430 .. class:: c_time_t
2431
2432 Represents the C :c:type:`time_t` datatype.
2433
2434 .. versionadded:: 3.12
2435
2436
2437 .. class:: c_ubyte
2438
2439 Represents the C :c:expr:`unsigned char` datatype, it interprets the value as
2440 small integer. The constructor accepts an optional integer initializer; no
2441 overflow checking is done.
2442
2443
2444 .. class:: c_uint
2445
2446 Represents the C :c:expr:`unsigned int` datatype. The constructor accepts an
2447 optional integer initializer; no overflow checking is done. On platforms
2448 where ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`.
2449
2450
2451 .. class:: c_uint8
2452
2453 Represents the C 8-bit :c:expr:`unsigned int` datatype. It is an alias for
2454 :class:`c_ubyte`.
2455
2456
2457 .. class:: c_uint16
2458
2459 Represents the C 16-bit :c:expr:`unsigned int` datatype. Usually an alias for
2460 :class:`c_ushort`.
2461
2462
2463 .. class:: c_uint32
2464
2465 Represents the C 32-bit :c:expr:`unsigned int` datatype. Usually an alias for
2466 :class:`c_uint`.
2467
2468
2469 .. class:: c_uint64
2470
2471 Represents the C 64-bit :c:expr:`unsigned int` datatype. Usually an alias for
2472 :class:`c_ulonglong`.
2473
2474
2475 .. class:: c_ulong
2476
2477 Represents the C :c:expr:`unsigned long` datatype. The constructor accepts an
2478 optional integer initializer; no overflow checking is done.
2479
2480
2481 .. class:: c_ulonglong
2482
2483 Represents the C :c:expr:`unsigned long long` datatype. The constructor
2484 accepts an optional integer initializer; no overflow checking is done.
2485
2486
2487 .. class:: c_ushort
2488
2489 Represents the C :c:expr:`unsigned short` datatype. The constructor accepts
2490 an optional integer initializer; no overflow checking is done.
2491
2492
2493 .. class:: c_void_p
2494
2495 Represents the C :c:expr:`void *` type. The value is represented as integer.
2496 The constructor accepts an optional integer initializer.
2497
2498
2499 .. class:: c_wchar
2500
2501 Represents the C :c:type:`wchar_t` datatype, and interprets the value as a
2502 single character unicode string. The constructor accepts an optional string
2503 initializer, the length of the string must be exactly one character.
2504
2505
2506 .. class:: c_wchar_p
2507
2508 Represents the C :c:expr:`wchar_t *` datatype, which must be a pointer to a
2509 zero-terminated wide character string. The constructor accepts an integer
2510 address, or a string.
2511
2512
2513 .. class:: c_bool
2514
2515 Represent the C :c:expr:`bool` datatype (more accurately, :c:expr:`_Bool` from
2516 C99). Its value can be ``True`` or ``False``, and the constructor accepts any object
2517 that has a truth value.
2518
2519
2520 .. class:: HRESULT
2521
2522 Represents a :c:type:`!HRESULT` value, which contains success or
2523 error information for a function or method call.
2524
2525 .. availability:: Windows
2526
2527
2528 .. class:: py_object
2529
2530 Represents the C :c:expr:`PyObject *` datatype. Calling this without an
2531 argument creates a ``NULL`` :c:expr:`PyObject *` pointer.
2532
2533 The :mod:`!ctypes.wintypes` module provides quite some other Windows specific
2534 data types, for example :c:type:`!HWND`, :c:type:`!WPARAM`, or :c:type:`!DWORD`.
2535 Some useful structures like :c:type:`!MSG` or :c:type:`!RECT` are also defined.
2536
2537
2538 .. _ctypes-structured-data-types:
2539
2540 Structured data types
2541 ^^^^^^^^^^^^^^^^^^^^^
2542
2543
2544 .. class:: Union(*args, **kw)
2545
2546 Abstract base class for unions in native byte order.
2547
2548
2549 .. class:: BigEndianUnion(*args, **kw)
2550
2551 Abstract base class for unions in *big endian* byte order.
2552
2553 .. versionadded:: 3.11
2554
2555 .. class:: LittleEndianUnion(*args, **kw)
2556
2557 Abstract base class for unions in *little endian* byte order.
2558
2559 .. versionadded:: 3.11
2560
2561 .. class:: BigEndianStructure(*args, **kw)
2562
2563 Abstract base class for structures in *big endian* byte order.
2564
2565
2566 .. class:: LittleEndianStructure(*args, **kw)
2567
2568 Abstract base class for structures in *little endian* byte order.
2569
2570 Structures and unions with non-native byte order cannot contain pointer type
2571 fields, or any other data types containing pointer type fields.
2572
2573
2574 .. class:: Structure(*args, **kw)
2575
2576 Abstract base class for structures in *native* byte order.
2577
2578 Concrete structure and union types must be created by subclassing one of these
2579 types, and at least define a :attr:`_fields_` class variable. :mod:`ctypes` will
2580 create :term:`descriptor`\s which allow reading and writing the fields by direct
2581 attribute accesses. These are the
2582
2583
2584 .. attribute:: _fields_
2585
2586 A sequence defining the structure fields. The items must be 2-tuples or
2587 3-tuples. The first item is the name of the field, the second item
2588 specifies the type of the field; it can be any ctypes data type.
2589
2590 For integer type fields like :class:`c_int`, a third optional item can be
2591 given. It must be a small positive integer defining the bit width of the
2592 field.
2593
2594 Field names must be unique within one structure or union. This is not
2595 checked, only one field can be accessed when names are repeated.
2596
2597 It is possible to define the :attr:`_fields_` class variable *after* the
2598 class statement that defines the Structure subclass, this allows creating
2599 data types that directly or indirectly reference themselves::
2600
2601 class List(Structure):
2602 pass
2603 List._fields_ = [("pnext", POINTER(List)),
2604 ...
2605 ]
2606
2607 The :attr:`_fields_` class variable must, however, be defined before the
2608 type is first used (an instance is created, :func:`sizeof` is called on it,
2609 and so on). Later assignments to the :attr:`_fields_` class variable will
2610 raise an AttributeError.
2611
2612 It is possible to define sub-subclasses of structure types, they inherit
2613 the fields of the base class plus the :attr:`_fields_` defined in the
2614 sub-subclass, if any.
2615
2616
2617 .. attribute:: _pack_
2618
2619 An optional small integer that allows overriding the alignment of
2620 structure fields in the instance. :attr:`_pack_` must already be defined
2621 when :attr:`_fields_` is assigned, otherwise it will have no effect.
2622 Setting this attribute to 0 is the same as not setting it at all.
2623
2624
2625 .. attribute:: _align_
2626
2627 An optional small integer that allows overriding the alignment of
2628 the structure when being packed or unpacked to/from memory.
2629 Setting this attribute to 0 is the same as not setting it at all.
2630
2631 .. versionadded:: 3.13
2632
2633 .. attribute:: _anonymous_
2634
2635 An optional sequence that lists the names of unnamed (anonymous) fields.
2636 :attr:`_anonymous_` must be already defined when :attr:`_fields_` is
2637 assigned, otherwise it will have no effect.
2638
2639 The fields listed in this variable must be structure or union type fields.
2640 :mod:`ctypes` will create descriptors in the structure type that allows
2641 accessing the nested fields directly, without the need to create the
2642 structure or union field.
2643
2644 Here is an example type (Windows)::
2645
2646 class _U(Union):
2647 _fields_ = [("lptdesc", POINTER(TYPEDESC)),
2648 ("lpadesc", POINTER(ARRAYDESC)),
2649 ("hreftype", HREFTYPE)]
2650
2651 class TYPEDESC(Structure):
2652 _anonymous_ = ("u",)
2653 _fields_ = [("u", _U),
2654 ("vt", VARTYPE)]
2655
2656
2657 The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field
2658 specifies which one of the union fields is valid. Since the ``u`` field
2659 is defined as anonymous field, it is now possible to access the members
2660 directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc``
2661 are equivalent, but the former is faster since it does not need to create
2662 a temporary union instance::
2663
2664 td = TYPEDESC()
2665 td.vt = VT_PTR
2666 td.lptdesc = POINTER(some_type)
2667 td.u.lptdesc = POINTER(some_type)
2668
2669 It is possible to define sub-subclasses of structures, they inherit the
2670 fields of the base class. If the subclass definition has a separate
2671 :attr:`_fields_` variable, the fields specified in this are appended to the
2672 fields of the base class.
2673
2674 Structure and union constructors accept both positional and keyword
2675 arguments. Positional arguments are used to initialize member fields in the
2676 same order as they are appear in :attr:`_fields_`. Keyword arguments in the
2677 constructor are interpreted as attribute assignments, so they will initialize
2678 :attr:`_fields_` with the same name, or create new attributes for names not
2679 present in :attr:`_fields_`.
2680
2681
2682 .. _ctypes-arrays-pointers:
2683
2684 Arrays and pointers
2685 ^^^^^^^^^^^^^^^^^^^
2686
2687 .. class:: Array(*args)
2688
2689 Abstract base class for arrays.
2690
2691 The recommended way to create concrete array types is by multiplying any
2692 :mod:`ctypes` data type with a non-negative integer. Alternatively, you can subclass
2693 this type and define :attr:`_length_` and :attr:`_type_` class variables.
2694 Array elements can be read and written using standard
2695 subscript and slice accesses; for slice reads, the resulting object is
2696 *not* itself an :class:`Array`.
2697
2698 Arrays are :ref:`generic <generics>` over the type of their elements.
2699
2700
2701 .. attribute:: _length_
2702
2703 A positive integer specifying the number of elements in the array.
2704 Out-of-range subscripts result in an :exc:`IndexError`. Will be
2705 returned by :func:`len`.
2706
2707
2708 .. attribute:: _type_
2709
2710 Specifies the type of each element in the array.
2711
2712
2713 Array subclass constructors accept positional arguments, used to
2714 initialize the elements in order.
2715
2716 .. function:: ARRAY(type, length)
2717
2718 Create an array.
2719 Equivalent to ``type * length``, where *type* is a
2720 :mod:`ctypes` data type and *length* an integer.
2721
2722 This function is :term:`soft deprecated` in favor of multiplication.
2723 There are no plans to remove it.
2724
2725
2726 .. class:: _Pointer
2727
2728 Private, abstract base class for pointers.
2729
2730 Concrete pointer types are created by calling :func:`POINTER` with the
2731 type that will be pointed to; this is done automatically by
2732 :func:`pointer`.
2733
2734 If a pointer points to an array, its elements can be read and
2735 written using standard subscript and slice accesses. Pointer objects
2736 have no size, so :func:`len` will raise :exc:`TypeError`. Negative
2737 subscripts will read from the memory *before* the pointer (as in C), and
2738 out-of-range subscripts will probably crash with an access violation (if
2739 you're lucky).
2740
2741
2742 .. attribute:: _type_
2743
2744 Specifies the type pointed to.
2745
2746 .. attribute:: contents
2747
2748 Returns the object to which to pointer points. Assigning to this
2749 attribute changes the pointer to point to the assigned object.