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