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