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