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