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