1 :mod:`ctypes` --- A foreign function library for Python
2 =======================================================
5 :synopsis: A foreign function library for Python.
6 .. moduleauthor:: Thomas Heller <theller@python.net>
11 :mod:`ctypes` is a foreign function library for Python. It provides C compatible
12 data types, and allows calling functions in DLLs or shared libraries. It can be
13 used to wrap these libraries in pure Python.
16 .. _ctypes-ctypes-tutorial:
21 Note: The code samples in this tutorial use :mod:`doctest` to make sure that
22 they actually work. Since some code samples behave differently under Linux,
23 Windows, or Mac OS X, they contain doctest directives in comments.
25 Note: Some code samples reference the ctypes :class:`c_int` type. This type is
26 an alias for the :class:`c_long` type on 32-bit systems. So, you should not be
27 confused if :class:`c_long` is printed if you would expect :class:`c_int` ---
28 they are actually the same type.
31 .. _ctypes-loading-dynamic-link-libraries:
33 Loading dynamic link libraries
34 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
36 :mod:`ctypes` exports the *cdll*, and on Windows *windll* and *oledll*
37 objects, for loading dynamic link libraries.
39 You load libraries by accessing them as attributes of these objects. *cdll*
40 loads libraries which export functions using the standard ``cdecl`` calling
41 convention, while *windll* libraries call functions using the ``stdcall``
42 calling convention. *oledll* also uses the ``stdcall`` calling convention, and
43 assumes the functions return a Windows :ctype:`HRESULT` error code. The error
44 code is used to automatically raise a :class:`WindowsError` exception when the
47 Here are some examples for Windows. Note that ``msvcrt`` is the MS standard C
48 library containing most standard C functions, and uses the cdecl calling
51 >>> from ctypes import *
52 >>> print windll.kernel32 # doctest: +WINDOWS
53 <WinDLL 'kernel32', handle ... at ...>
54 >>> print cdll.msvcrt # doctest: +WINDOWS
55 <CDLL 'msvcrt', handle ... at ...>
56 >>> libc = cdll.msvcrt # doctest: +WINDOWS
59 Windows appends the usual ``.dll`` file suffix automatically.
61 On Linux, it is required to specify the filename *including* the extension to
62 load a library, so attribute access can not be used to load libraries. Either the
63 :meth:`LoadLibrary` method of the dll loaders should be used, or you should load
64 the library by creating an instance of CDLL by calling the constructor::
66 >>> cdll.LoadLibrary("libc.so.6") # doctest: +LINUX
67 <CDLL 'libc.so.6', handle ... at ...>
68 >>> libc = CDLL("libc.so.6") # doctest: +LINUX
69 >>> libc # doctest: +LINUX
70 <CDLL 'libc.so.6', handle ... at ...>
73 .. XXX Add section for Mac OS X.
76 .. _ctypes-accessing-functions-from-loaded-dlls:
78 Accessing functions from loaded dlls
79 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
81 Functions are accessed as attributes of dll objects::
83 >>> from ctypes import *
85 <_FuncPtr object at 0x...>
86 >>> print windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
87 <_FuncPtr object at 0x...>
88 >>> print windll.kernel32.MyOwnFunction # doctest: +WINDOWS
89 Traceback (most recent call last):
90 File "<stdin>", line 1, in ?
91 File "ctypes.py", line 239, in __getattr__
92 func = _StdcallFuncPtr(name, self)
93 AttributeError: function 'MyOwnFunction' not found
96 Note that win32 system dlls like ``kernel32`` and ``user32`` often export ANSI
97 as well as UNICODE versions of a function. The UNICODE version is exported with
98 an ``W`` appended to the name, while the ANSI version is exported with an ``A``
99 appended to the name. The win32 ``GetModuleHandle`` function, which returns a
100 *module handle* for a given module name, has the following C prototype, and a
101 macro is used to expose one of them as ``GetModuleHandle`` depending on whether
102 UNICODE is defined or not::
105 HMODULE GetModuleHandleA(LPCSTR lpModuleName);
106 /* UNICODE version */
107 HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
109 *windll* does not try to select one of them by magic, you must access the
110 version you need by specifying ``GetModuleHandleA`` or ``GetModuleHandleW``
111 explicitly, and then call it with strings or unicode strings
114 Sometimes, dlls export functions with names which aren't valid Python
115 identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use
116 :func:`getattr` to retrieve the function::
118 >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") # doctest: +WINDOWS
119 <_FuncPtr object at 0x...>
122 On Windows, some dlls export functions not by name but by ordinal. These
123 functions can be accessed by indexing the dll object with the ordinal number::
125 >>> cdll.kernel32[1] # doctest: +WINDOWS
126 <_FuncPtr object at 0x...>
127 >>> cdll.kernel32[0] # doctest: +WINDOWS
128 Traceback (most recent call last):
129 File "<stdin>", line 1, in ?
130 File "ctypes.py", line 310, in __getitem__
131 func = _StdcallFuncPtr(name, self)
132 AttributeError: function ordinal 0 not found
136 .. _ctypes-calling-functions:
141 You can call these functions like any other Python callable. This example uses
142 the ``time()`` function, which returns system time in seconds since the Unix
143 epoch, and the ``GetModuleHandleA()`` function, which returns a win32 module
146 This example calls both functions with a NULL pointer (``None`` should be used
147 as the NULL pointer)::
149 >>> print libc.time(None) # doctest: +SKIP
151 >>> print hex(windll.kernel32.GetModuleHandleA(None)) # doctest: +WINDOWS
155 :mod:`ctypes` tries to protect you from calling functions with the wrong number
156 of arguments or the wrong calling convention. Unfortunately this only works on
157 Windows. It does this by examining the stack after the function returns, so
158 although an error is raised the function *has* been called::
160 >>> windll.kernel32.GetModuleHandleA() # doctest: +WINDOWS
161 Traceback (most recent call last):
162 File "<stdin>", line 1, in ?
163 ValueError: Procedure probably called with not enough arguments (4 bytes missing)
164 >>> windll.kernel32.GetModuleHandleA(0, 0) # doctest: +WINDOWS
165 Traceback (most recent call last):
166 File "<stdin>", line 1, in ?
167 ValueError: Procedure probably called with too many arguments (4 bytes in excess)
170 The same exception is raised when you call an ``stdcall`` function with the
171 ``cdecl`` calling convention, or vice versa::
173 >>> cdll.kernel32.GetModuleHandleA(None) # doctest: +WINDOWS
174 Traceback (most recent call last):
175 File "<stdin>", line 1, in ?
176 ValueError: Procedure probably called with not enough arguments (4 bytes missing)
179 >>> windll.msvcrt.printf("spam") # doctest: +WINDOWS
180 Traceback (most recent call last):
181 File "<stdin>", line 1, in ?
182 ValueError: Procedure probably called with too many arguments (4 bytes in excess)
185 To find out the correct calling convention you have to look into the C header
186 file or the documentation for the function you want to call.
188 On Windows, :mod:`ctypes` uses win32 structured exception handling to prevent
189 crashes from general protection faults when functions are called with invalid
192 >>> windll.kernel32.GetModuleHandleA(32) # doctest: +WINDOWS
193 Traceback (most recent call last):
194 File "<stdin>", line 1, in ?
195 WindowsError: exception: access violation reading 0x00000020
198 There are, however, enough ways to crash Python with :mod:`ctypes`, so you
199 should be careful anyway.
201 ``None``, integers, longs, byte strings and unicode strings are the only native
202 Python objects that can directly be used as parameters in these function calls.
203 ``None`` is passed as a C ``NULL`` pointer, byte strings and unicode strings are
204 passed as pointer to the memory block that contains their data (:ctype:`char *`
205 or :ctype:`wchar_t *`). Python integers and Python longs are passed as the
206 platforms default C :ctype:`int` type, their value is masked to fit into the C
209 Before we move on calling functions with other parameter types, we have to learn
210 more about :mod:`ctypes` data types.
213 .. _ctypes-fundamental-data-types:
215 Fundamental data types
216 ^^^^^^^^^^^^^^^^^^^^^^
218 :mod:`ctypes` defines a number of primitive C compatible data types :
220 +----------------------+----------------------------------------+----------------------------+
221 | ctypes type | C type | Python type |
222 +======================+========================================+============================+
223 | :class:`c_char` | :ctype:`char` | 1-character string |
224 +----------------------+----------------------------------------+----------------------------+
225 | :class:`c_wchar` | :ctype:`wchar_t` | 1-character unicode string |
226 +----------------------+----------------------------------------+----------------------------+
227 | :class:`c_byte` | :ctype:`char` | int/long |
228 +----------------------+----------------------------------------+----------------------------+
229 | :class:`c_ubyte` | :ctype:`unsigned char` | int/long |
230 +----------------------+----------------------------------------+----------------------------+
231 | :class:`c_short` | :ctype:`short` | int/long |
232 +----------------------+----------------------------------------+----------------------------+
233 | :class:`c_ushort` | :ctype:`unsigned short` | int/long |
234 +----------------------+----------------------------------------+----------------------------+
235 | :class:`c_int` | :ctype:`int` | int/long |
236 +----------------------+----------------------------------------+----------------------------+
237 | :class:`c_uint` | :ctype:`unsigned int` | int/long |
238 +----------------------+----------------------------------------+----------------------------+
239 | :class:`c_long` | :ctype:`long` | int/long |
240 +----------------------+----------------------------------------+----------------------------+
241 | :class:`c_ulong` | :ctype:`unsigned long` | int/long |
242 +----------------------+----------------------------------------+----------------------------+
243 | :class:`c_longlong` | :ctype:`__int64` or :ctype:`long long` | int/long |
244 +----------------------+----------------------------------------+----------------------------+
245 | :class:`c_ulonglong` | :ctype:`unsigned __int64` or | int/long |
246 | | :ctype:`unsigned long long` | |
247 +----------------------+----------------------------------------+----------------------------+
248 | :class:`c_float` | :ctype:`float` | float |
249 +----------------------+----------------------------------------+----------------------------+
250 | :class:`c_double` | :ctype:`double` | float |
251 +----------------------+----------------------------------------+----------------------------+
252 | :class:`c_longdouble`| :ctype:`long double` | float |
253 +----------------------+----------------------------------------+----------------------------+
254 | :class:`c_char_p` | :ctype:`char *` (NUL terminated) | string or ``None`` |
255 +----------------------+----------------------------------------+----------------------------+
256 | :class:`c_wchar_p` | :ctype:`wchar_t *` (NUL terminated) | unicode or ``None`` |
257 +----------------------+----------------------------------------+----------------------------+
258 | :class:`c_void_p` | :ctype:`void *` | int/long or ``None`` |
259 +----------------------+----------------------------------------+----------------------------+
261 All these types can be created by calling them with an optional initializer of
262 the correct type and value::
266 >>> c_char_p("Hello, World")
267 c_char_p('Hello, World')
272 Since these types are mutable, their value can also be changed afterwards::
284 Assigning a new value to instances of the pointer types :class:`c_char_p`,
285 :class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they
286 point to, *not the contents* of the memory block (of course not, because Python
287 strings are immutable)::
289 >>> s = "Hello, World"
290 >>> c_s = c_char_p(s)
292 c_char_p('Hello, World')
293 >>> c_s.value = "Hi, there"
295 c_char_p('Hi, there')
296 >>> print s # first string is unchanged
300 You should be careful, however, not to pass them to functions expecting pointers
301 to mutable memory. If you need mutable memory blocks, ctypes has a
302 :func:`create_string_buffer` function which creates these in various ways. The
303 current memory block contents can be accessed (or changed) with the ``raw``
304 property; if you want to access it as NUL terminated string, use the ``value``
307 >>> from ctypes import *
308 >>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes
309 >>> print sizeof(p), repr(p.raw)
311 >>> p = create_string_buffer("Hello") # create a buffer containing a NUL terminated string
312 >>> print sizeof(p), repr(p.raw)
314 >>> print repr(p.value)
316 >>> p = create_string_buffer("Hello", 10) # create a 10 byte buffer
317 >>> print sizeof(p), repr(p.raw)
318 10 'Hello\x00\x00\x00\x00\x00'
320 >>> print sizeof(p), repr(p.raw)
321 10 'Hi\x00lo\x00\x00\x00\x00\x00'
324 The :func:`create_string_buffer` function replaces the :func:`c_buffer` function
325 (which is still available as an alias), as well as the :func:`c_string` function
326 from earlier ctypes releases. To create a mutable memory block containing
327 unicode characters of the C type :ctype:`wchar_t` use the
328 :func:`create_unicode_buffer` function.
331 .. _ctypes-calling-functions-continued:
333 Calling functions, continued
334 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
336 Note that printf prints to the real standard output channel, *not* to
337 :data:`sys.stdout`, so these examples will only work at the console prompt, not
338 from within *IDLE* or *PythonWin*::
340 >>> printf = libc.printf
341 >>> printf("Hello, %s\n", "World!")
344 >>> printf("Hello, %S\n", u"World!")
347 >>> printf("%d bottles of beer\n", 42)
350 >>> printf("%f bottles of beer\n", 42.5)
351 Traceback (most recent call last):
352 File "<stdin>", line 1, in ?
353 ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2
356 As has been mentioned before, all Python types except integers, strings, and
357 unicode strings have to be wrapped in their corresponding :mod:`ctypes` type, so
358 that they can be converted to the required C data type::
360 >>> printf("An int %d, a double %f\n", 1234, c_double(3.14))
361 An int 1234, a double 3.140000
366 .. _ctypes-calling-functions-with-own-custom-data-types:
368 Calling functions with your own custom data types
369 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
371 You can also customize :mod:`ctypes` argument conversion to allow instances of
372 your own classes be used as function arguments. :mod:`ctypes` looks for an
373 :attr:`_as_parameter_` attribute and uses this as the function argument. Of
374 course, it must be one of integer, string, or unicode::
376 >>> class Bottles(object):
377 ... def __init__(self, number):
378 ... self._as_parameter_ = number
380 >>> bottles = Bottles(42)
381 >>> printf("%d bottles of beer\n", bottles)
386 If you don't want to store the instance's data in the :attr:`_as_parameter_`
387 instance variable, you could define a :func:`property` which makes the data
391 .. _ctypes-specifying-required-argument-types:
393 Specifying the required argument types (function prototypes)
394 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
396 It is possible to specify the required argument types of functions exported from
397 DLLs by setting the :attr:`argtypes` attribute.
399 :attr:`argtypes` must be a sequence of C data types (the ``printf`` function is
400 probably not a good example here, because it takes a variable number and
401 different types of parameters depending on the format string, on the other hand
402 this is quite handy to experiment with this feature)::
404 >>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
405 >>> printf("String '%s', Int %d, Double %f\n", "Hi", 10, 2.2)
406 String 'Hi', Int 10, Double 2.200000
410 Specifying a format protects against incompatible argument types (just as a
411 prototype for a C function), and tries to convert the arguments to valid types::
413 >>> printf("%d %d %d", 1, 2, 3)
414 Traceback (most recent call last):
415 File "<stdin>", line 1, in ?
416 ArgumentError: argument 2: exceptions.TypeError: wrong type
417 >>> printf("%s %d %f\n", "X", 2, 3)
422 If you have defined your own classes which you pass to function calls, you have
423 to implement a :meth:`from_param` class method for them to be able to use them
424 in the :attr:`argtypes` sequence. The :meth:`from_param` class method receives
425 the Python object passed to the function call, it should do a typecheck or
426 whatever is needed to make sure this object is acceptable, and then return the
427 object itself, its :attr:`_as_parameter_` attribute, or whatever you want to
428 pass as the C function argument in this case. Again, the result should be an
429 integer, string, unicode, a :mod:`ctypes` instance, or an object with an
430 :attr:`_as_parameter_` attribute.
433 .. _ctypes-return-types:
438 By default functions are assumed to return the C :ctype:`int` type. Other
439 return types can be specified by setting the :attr:`restype` attribute of the
442 Here is a more advanced example, it uses the ``strchr`` function, which expects
443 a string pointer and a char, and returns a pointer to a string::
445 >>> strchr = libc.strchr
446 >>> strchr("abcdef", ord("d")) # doctest: +SKIP
448 >>> strchr.restype = c_char_p # c_char_p is a pointer to a string
449 >>> strchr("abcdef", ord("d"))
451 >>> print strchr("abcdef", ord("x"))
455 If you want to avoid the ``ord("x")`` calls above, you can set the
456 :attr:`argtypes` attribute, and the second argument will be converted from a
457 single character Python string into a C char::
459 >>> strchr.restype = c_char_p
460 >>> strchr.argtypes = [c_char_p, c_char]
461 >>> strchr("abcdef", "d")
463 >>> strchr("abcdef", "def")
464 Traceback (most recent call last):
465 File "<stdin>", line 1, in ?
466 ArgumentError: argument 2: exceptions.TypeError: one character string expected
467 >>> print strchr("abcdef", "x")
469 >>> strchr("abcdef", "d")
473 You can also use a callable Python object (a function or a class for example) as
474 the :attr:`restype` attribute, if the foreign function returns an integer. The
475 callable will be called with the *integer* the C function returns, and the
476 result of this call will be used as the result of your function call. This is
477 useful to check for error return values and automatically raise an exception::
479 >>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
480 >>> def ValidHandle(value):
486 >>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS
487 >>> GetModuleHandle(None) # doctest: +WINDOWS
489 >>> GetModuleHandle("something silly") # doctest: +WINDOWS
490 Traceback (most recent call last):
491 File "<stdin>", line 1, in ?
492 File "<stdin>", line 3, in ValidHandle
493 WindowsError: [Errno 126] The specified module could not be found.
496 ``WinError`` is a function which will call Windows ``FormatMessage()`` api to
497 get the string representation of an error code, and *returns* an exception.
498 ``WinError`` takes an optional error code parameter, if no one is used, it calls
499 :func:`GetLastError` to retrieve it.
501 Please note that a much more powerful error checking mechanism is available
502 through the :attr:`errcheck` attribute; see the reference manual for details.
505 .. _ctypes-passing-pointers:
507 Passing pointers (or: passing parameters by reference)
508 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
510 Sometimes a C api function expects a *pointer* to a data type as parameter,
511 probably to write into the corresponding location, or if the data is too large
512 to be passed by value. This is also known as *passing parameters by reference*.
514 :mod:`ctypes` exports the :func:`byref` function which is used to pass
515 parameters by reference. The same effect can be achieved with the
516 :func:`pointer` function, although :func:`pointer` does a lot more work since it
517 constructs a real pointer object, so it is faster to use :func:`byref` if you
518 don't need the pointer object in Python itself::
522 >>> s = create_string_buffer('\000' * 32)
523 >>> print i.value, f.value, repr(s.value)
525 >>> libc.sscanf("1 3.14 Hello", "%d %f %s",
526 ... byref(i), byref(f), s)
528 >>> print i.value, f.value, repr(s.value)
529 1 3.1400001049 'Hello'
533 .. _ctypes-structures-unions:
535 Structures and unions
536 ^^^^^^^^^^^^^^^^^^^^^
538 Structures and unions must derive from the :class:`Structure` and :class:`Union`
539 base classes which are defined in the :mod:`ctypes` module. Each subclass must
540 define a :attr:`_fields_` attribute. :attr:`_fields_` must be a list of
541 *2-tuples*, containing a *field name* and a *field type*.
543 The field type must be a :mod:`ctypes` type like :class:`c_int`, or any other
544 derived :mod:`ctypes` type: structure, union, array, pointer.
546 Here is a simple example of a POINT structure, which contains two integers named
547 *x* and *y*, and also shows how to initialize a structure in the constructor::
549 >>> from ctypes import *
550 >>> class POINT(Structure):
551 ... _fields_ = [("x", c_int),
554 >>> point = POINT(10, 20)
555 >>> print point.x, point.y
557 >>> point = POINT(y=5)
558 >>> print point.x, point.y
561 Traceback (most recent call last):
562 File "<stdin>", line 1, in ?
563 ValueError: too many initializers
566 You can, however, build much more complicated structures. Structures can itself
567 contain other structures by using a structure as a field type.
569 Here is a RECT structure which contains two POINTs named *upperleft* and
572 >>> class RECT(Structure):
573 ... _fields_ = [("upperleft", POINT),
574 ... ("lowerright", POINT)]
577 >>> print rc.upperleft.x, rc.upperleft.y
579 >>> print rc.lowerright.x, rc.lowerright.y
583 Nested structures can also be initialized in the constructor in several ways::
585 >>> r = RECT(POINT(1, 2), POINT(3, 4))
586 >>> r = RECT((1, 2), (3, 4))
588 Field :term:`descriptor`\s can be retrieved from the *class*, they are useful
589 for debugging because they can provide useful information::
592 <Field type=c_long, ofs=0, size=4>
594 <Field type=c_long, ofs=4, size=4>
598 .. _ctypes-structureunion-alignment-byte-order:
600 Structure/union alignment and byte order
601 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
603 By default, Structure and Union fields are aligned in the same way the C
604 compiler does it. It is possible to override this behavior be specifying a
605 :attr:`_pack_` class attribute in the subclass definition. This must be set to a
606 positive integer and specifies the maximum alignment for the fields. This is
607 what ``#pragma pack(n)`` also does in MSVC.
609 :mod:`ctypes` uses the native byte order for Structures and Unions. To build
610 structures with non-native byte order, you can use one of the
611 :class:`BigEndianStructure`, :class:`LittleEndianStructure`,
612 :class:`BigEndianUnion`, and :class:`LittleEndianUnion` base classes. These
613 classes cannot contain pointer fields.
616 .. _ctypes-bit-fields-in-structures-unions:
618 Bit fields in structures and unions
619 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
621 It is possible to create structures and unions containing bit fields. Bit fields
622 are only possible for integer fields, the bit width is specified as the third
623 item in the :attr:`_fields_` tuples::
625 >>> class Int(Structure):
626 ... _fields_ = [("first_16", c_int, 16),
627 ... ("second_16", c_int, 16)]
629 >>> print Int.first_16
630 <Field type=c_long, ofs=0:0, bits=16>
631 >>> print Int.second_16
632 <Field type=c_long, ofs=0:16, bits=16>
641 Arrays are sequences, containing a fixed number of instances of the same type.
643 The recommended way to create array types is by multiplying a data type with a
646 TenPointsArrayType = POINT * 10
648 Here is an example of an somewhat artificial data type, a structure containing 4
649 POINTs among other stuff::
651 >>> from ctypes import *
652 >>> class POINT(Structure):
653 ... _fields_ = ("x", c_int), ("y", c_int)
655 >>> class MyStruct(Structure):
656 ... _fields_ = [("a", c_int),
658 ... ("point_array", POINT * 4)]
660 >>> print len(MyStruct().point_array)
664 Instances are created in the usual way, by calling the class::
666 arr = TenPointsArrayType()
670 The above code print a series of ``0 0`` lines, because the array contents is
671 initialized to zeros.
673 Initializers of the correct type can also be specified::
675 >>> from ctypes import *
676 >>> TenIntegers = c_int * 10
677 >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
679 <c_long_Array_10 object at 0x...>
680 >>> for i in ii: print i,
691 Pointer instances are created by calling the :func:`pointer` function on a
694 >>> from ctypes import *
699 Pointer instances have a :attr:`contents` attribute which returns the object to
700 which the pointer points, the ``i`` object above::
706 Note that :mod:`ctypes` does not have OOR (original object return), it constructs a
707 new, equivalent object each time you retrieve an attribute::
711 >>> pi.contents is pi.contents
715 Assigning another :class:`c_int` instance to the pointer's contents attribute
716 would cause the pointer to point to the memory location where this is stored::
724 .. XXX Document dereferencing pointers, and that it is preferred over the
727 Pointer instances can also be indexed with integers::
733 Assigning to an integer index changes the pointed to value::
742 It is also possible to use indexes different from 0, but you must know what
743 you're doing, just as in C: You can access or change arbitrary memory locations.
744 Generally you only use this feature if you receive a pointer from a C function,
745 and you *know* that the pointer actually points to an array instead of a single
748 Behind the scenes, the :func:`pointer` function does more than simply create
749 pointer instances, it has to create pointer *types* first. This is done with
750 the :func:`POINTER` function, which accepts any :mod:`ctypes` type, and returns
753 >>> PI = POINTER(c_int)
755 <class 'ctypes.LP_c_long'>
757 Traceback (most recent call last):
758 File "<stdin>", line 1, in ?
759 TypeError: expected c_long instead of int
761 <ctypes.LP_c_long object at 0x...>
764 Calling the pointer type without an argument creates a ``NULL`` pointer.
765 ``NULL`` pointers have a ``False`` boolean value::
767 >>> null_ptr = POINTER(c_int)()
768 >>> print bool(null_ptr)
772 :mod:`ctypes` checks for ``NULL`` when dereferencing pointers (but dereferencing
773 invalid non-\ ``NULL`` pointers would crash Python)::
776 Traceback (most recent call last):
778 ValueError: NULL pointer access
781 >>> null_ptr[0] = 1234
782 Traceback (most recent call last):
784 ValueError: NULL pointer access
788 .. _ctypes-type-conversions:
793 Usually, ctypes does strict type checking. This means, if you have
794 ``POINTER(c_int)`` in the :attr:`argtypes` list of a function or as the type of
795 a member field in a structure definition, only instances of exactly the same
796 type are accepted. There are some exceptions to this rule, where ctypes accepts
797 other objects. For example, you can pass compatible array instances instead of
798 pointer types. So, for ``POINTER(c_int)``, ctypes accepts an array of c_int::
800 >>> class Bar(Structure):
801 ... _fields_ = [("count", c_int), ("values", POINTER(c_int))]
804 >>> bar.values = (c_int * 3)(1, 2, 3)
806 >>> for i in range(bar.count):
807 ... print bar.values[i]
814 To set a POINTER type field to ``NULL``, you can assign ``None``::
816 >>> bar.values = None
819 .. XXX list other conversions...
821 Sometimes you have instances of incompatible types. In C, you can cast one type
822 into another type. :mod:`ctypes` provides a :func:`cast` function which can be
823 used in the same way. The ``Bar`` structure defined above accepts
824 ``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field,
825 but not instances of other types::
827 >>> bar.values = (c_byte * 4)()
828 Traceback (most recent call last):
829 File "<stdin>", line 1, in ?
830 TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
833 For these cases, the :func:`cast` function is handy.
835 The :func:`cast` function can be used to cast a ctypes instance into a pointer
836 to a different ctypes data type. :func:`cast` takes two parameters, a ctypes
837 object that is or can be converted to a pointer of some kind, and a ctypes
838 pointer type. It returns an instance of the second argument, which references
839 the same memory block as the first argument::
841 >>> a = (c_byte * 4)()
842 >>> cast(a, POINTER(c_int))
843 <ctypes.LP_c_long object at ...>
846 So, :func:`cast` can be used to assign to the ``values`` field of ``Bar`` the
850 >>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
851 >>> print bar.values[0]
856 .. _ctypes-incomplete-types:
861 *Incomplete Types* are structures, unions or arrays whose members are not yet
862 specified. In C, they are specified by forward declarations, which are defined
865 struct cell; /* forward declaration */
872 The straightforward translation into ctypes code would be this, but it does not
875 >>> class cell(Structure):
876 ... _fields_ = [("name", c_char_p),
877 ... ("next", POINTER(cell))]
879 Traceback (most recent call last):
880 File "<stdin>", line 1, in ?
881 File "<stdin>", line 2, in cell
882 NameError: name 'cell' is not defined
885 because the new ``class cell`` is not available in the class statement itself.
886 In :mod:`ctypes`, we can define the ``cell`` class and set the :attr:`_fields_`
887 attribute later, after the class statement::
889 >>> from ctypes import *
890 >>> class cell(Structure):
893 >>> cell._fields_ = [("name", c_char_p),
894 ... ("next", POINTER(cell))]
897 Lets try it. We create two instances of ``cell``, and let them point to each
898 other, and finally follow the pointer chain a few times::
904 >>> c1.next = pointer(c2)
905 >>> c2.next = pointer(c1)
907 >>> for i in range(8):
911 foo bar foo bar foo bar foo bar
915 .. _ctypes-callback-functions:
920 :mod:`ctypes` allows to create C callable function pointers from Python callables.
921 These are sometimes called *callback functions*.
923 First, you must create a class for the callback function, the class knows the
924 calling convention, the return type, and the number and types of arguments this
925 function will receive.
927 The CFUNCTYPE factory function creates types for callback functions using the
928 normal cdecl calling convention, and, on Windows, the WINFUNCTYPE factory
929 function creates types for callback functions using the stdcall calling
932 Both of these factory functions are called with the result type as first
933 argument, and the callback functions expected argument types as the remaining
936 I will present an example here which uses the standard C library's :func:`qsort`
937 function, this is used to sort items with the help of a callback function.
938 :func:`qsort` will be used to sort an array of integers::
940 >>> IntArray5 = c_int * 5
941 >>> ia = IntArray5(5, 1, 7, 33, 99)
942 >>> qsort = libc.qsort
943 >>> qsort.restype = None
946 :func:`qsort` must be called with a pointer to the data to sort, the number of
947 items in the data array, the size of one item, and a pointer to the comparison
948 function, the callback. The callback will then be called with two pointers to
949 items, and it must return a negative integer if the first item is smaller than
950 the second, a zero if they are equal, and a positive integer else.
952 So our callback function receives pointers to integers, and must return an
953 integer. First we create the ``type`` for the callback function::
955 >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
958 For the first implementation of the callback function, we simply print the
959 arguments we get, and return 0 (incremental development ;-)::
961 >>> def py_cmp_func(a, b):
962 ... print "py_cmp_func", a, b
967 Create the C callable callback::
969 >>> cmp_func = CMPFUNC(py_cmp_func)
972 And we're ready to go::
974 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
975 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
976 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
977 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
978 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
979 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
980 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
981 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
982 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
983 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
984 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
987 We know how to access the contents of a pointer, so lets redefine our callback::
989 >>> def py_cmp_func(a, b):
990 ... print "py_cmp_func", a[0], b[0]
993 >>> cmp_func = CMPFUNC(py_cmp_func)
996 Here is what we get on Windows::
998 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
1011 It is funny to see that on linux the sort function seems to work much more
1012 efficiently, it is doing less comparisons::
1014 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX
1022 Ah, we're nearly done! The last step is to actually compare the two items and
1023 return a useful result::
1025 >>> def py_cmp_func(a, b):
1026 ... print "py_cmp_func", a[0], b[0]
1027 ... return a[0] - b[0]
1031 Final run on Windows::
1033 >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +WINDOWS
1048 >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX
1056 It is quite interesting to see that the Windows :func:`qsort` function needs
1057 more comparisons than the linux version!
1059 As we can easily check, our array is sorted now::
1061 >>> for i in ia: print i,
1066 **Important note for callback functions:**
1068 Make sure you keep references to CFUNCTYPE objects as long as they are used from
1069 C code. :mod:`ctypes` doesn't, and if you don't, they may be garbage collected,
1070 crashing your program when a callback is made.
1073 .. _ctypes-accessing-values-exported-from-dlls:
1075 Accessing values exported from dlls
1076 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1078 Some shared libraries not only export functions, they also export variables. An
1079 example in the Python library itself is the ``Py_OptimizeFlag``, an integer set
1080 to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on
1083 :mod:`ctypes` can access values like this with the :meth:`in_dll` class methods of
1084 the type. *pythonapi* is a predefined symbol giving access to the Python C
1087 >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
1092 If the interpreter would have been started with :option:`-O`, the sample would
1093 have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been
1096 An extended example which also demonstrates the use of pointers accesses the
1097 ``PyImport_FrozenModules`` pointer exported by Python.
1099 Quoting the Python docs: *This pointer is initialized to point to an array of
1100 "struct _frozen" records, terminated by one whose members are all NULL or zero.
1101 When a frozen module is imported, it is searched in this table. Third-party code
1102 could play tricks with this to provide a dynamically created collection of
1105 So manipulating this pointer could even prove useful. To restrict the example
1106 size, we show only how this table can be read with :mod:`ctypes`::
1108 >>> from ctypes import *
1110 >>> class struct_frozen(Structure):
1111 ... _fields_ = [("name", c_char_p),
1112 ... ("code", POINTER(c_ubyte)),
1113 ... ("size", c_int)]
1117 We have defined the ``struct _frozen`` data type, so we can get the pointer to
1120 >>> FrozenTable = POINTER(struct_frozen)
1121 >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
1124 Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we
1125 can iterate over it, but we just have to make sure that our loop terminates,
1126 because pointers have no size. Sooner or later it would probably crash with an
1127 access violation or whatever, so it's better to break out of the loop when we
1128 hit the NULL entry::
1130 >>> for item in table:
1131 ... print item.name, item.size
1132 ... if item.name is None:
1141 The fact that standard Python has a frozen module and a frozen package
1142 (indicated by the negative size member) is not well known, it is only used for
1143 testing. Try it out with ``import __hello__`` for example.
1146 .. _ctypes-surprises:
1151 There are some edges in :mod:`ctypes` where you may be expect something else than
1152 what actually happens.
1154 Consider the following example::
1156 >>> from ctypes import *
1157 >>> class POINT(Structure):
1158 ... _fields_ = ("x", c_int), ("y", c_int)
1160 >>> class RECT(Structure):
1161 ... _fields_ = ("a", POINT), ("b", POINT)
1163 >>> p1 = POINT(1, 2)
1164 >>> p2 = POINT(3, 4)
1165 >>> rc = RECT(p1, p2)
1166 >>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
1168 >>> # now swap the two points
1169 >>> rc.a, rc.b = rc.b, rc.a
1170 >>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
1174 Hm. We certainly expected the last statement to print ``3 4 1 2``. What
1175 happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
1177 >>> temp0, temp1 = rc.b, rc.a
1182 Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of
1183 the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer
1184 contents of ``temp0`` into ``rc`` 's buffer. This, in turn, changes the
1185 contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have
1186 the expected effect.
1188 Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
1189 doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing
1190 the root-object's underlying buffer.
1192 Another example that may behave different from what one would expect is this::
1195 >>> s.value = "abc def ghi"
1198 >>> s.value is s.value
1202 Why is it printing ``False``? ctypes instances are objects containing a memory
1203 block plus some :term:`descriptor`\s accessing the contents of the memory.
1204 Storing a Python object in the memory block does not store the object itself,
1205 instead the ``contents`` of the object is stored. Accessing the contents again
1206 constructs a new Python object each time!
1209 .. _ctypes-variable-sized-data-types:
1211 Variable-sized data types
1212 ^^^^^^^^^^^^^^^^^^^^^^^^^
1214 :mod:`ctypes` provides some support for variable-sized arrays and structures.
1216 The :func:`resize` function can be used to resize the memory buffer of an
1217 existing ctypes object. The function takes the object as first argument, and
1218 the requested size in bytes as the second argument. The memory block cannot be
1219 made smaller than the natural memory block specified by the objects type, a
1220 :exc:`ValueError` is raised if this is tried::
1222 >>> short_array = (c_short * 4)()
1223 >>> print sizeof(short_array)
1225 >>> resize(short_array, 4)
1226 Traceback (most recent call last):
1228 ValueError: minimum size is 8
1229 >>> resize(short_array, 32)
1230 >>> sizeof(short_array)
1232 >>> sizeof(type(short_array))
1236 This is nice and fine, but how would one access the additional elements
1237 contained in this array? Since the type still only knows about 4 elements, we
1238 get errors accessing other elements::
1243 Traceback (most recent call last):
1245 IndexError: invalid index
1248 Another way to use variable-sized data types with :mod:`ctypes` is to use the
1249 dynamic nature of Python, and (re-)define the data type after the required size
1250 is already known, on a case by case basis.
1253 .. _ctypes-ctypes-reference:
1259 .. _ctypes-finding-shared-libraries:
1261 Finding shared libraries
1262 ^^^^^^^^^^^^^^^^^^^^^^^^
1264 When programming in a compiled language, shared libraries are accessed when
1265 compiling/linking a program, and when the program is run.
1267 The purpose of the :func:`find_library` function is to locate a library in a way
1268 similar to what the compiler does (on platforms with several versions of a
1269 shared library the most recent should be loaded), while the ctypes library
1270 loaders act like when a program is run, and call the runtime loader directly.
1272 The :mod:`ctypes.util` module provides a function which can help to determine the
1276 .. data:: find_library(name)
1277 :module: ctypes.util
1280 Try to find a library and return a pathname. *name* is the library name without
1281 any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this
1282 is the form used for the posix linker option :option:`-l`). If no library can
1283 be found, returns ``None``.
1285 The exact functionality is system dependent.
1287 On Linux, :func:`find_library` tries to run external programs
1288 (``/sbin/ldconfig``, ``gcc``, and ``objdump``) to find the library file. It
1289 returns the filename of the library file. Here are some examples::
1291 >>> from ctypes.util import find_library
1292 >>> find_library("m")
1294 >>> find_library("c")
1296 >>> find_library("bz2")
1300 On OS X, :func:`find_library` tries several predefined naming schemes and paths
1301 to locate the library, and returns a full pathname if successful::
1303 >>> from ctypes.util import find_library
1304 >>> find_library("c")
1305 '/usr/lib/libc.dylib'
1306 >>> find_library("m")
1307 '/usr/lib/libm.dylib'
1308 >>> find_library("bz2")
1309 '/usr/lib/libbz2.dylib'
1310 >>> find_library("AGL")
1311 '/System/Library/Frameworks/AGL.framework/AGL'
1314 On Windows, :func:`find_library` searches along the system search path, and
1315 returns the full pathname, but since there is no predefined naming scheme a call
1316 like ``find_library("c")`` will fail and return ``None``.
1318 If wrapping a shared library with :mod:`ctypes`, it *may* be better to determine
1319 the shared library name at development type, and hardcode that into the wrapper
1320 module instead of using :func:`find_library` to locate the library at runtime.
1323 .. _ctypes-loading-shared-libraries:
1325 Loading shared libraries
1326 ^^^^^^^^^^^^^^^^^^^^^^^^
1328 There are several ways to loaded shared libraries into the Python process. One
1329 way is to instantiate one of the following classes:
1332 .. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
1334 Instances of this class represent loaded shared libraries. Functions in these
1335 libraries use the standard C calling convention, and are assumed to return
1339 .. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
1341 Windows only: Instances of this class represent loaded shared libraries,
1342 functions in these libraries use the ``stdcall`` calling convention, and are
1343 assumed to return the windows specific :class:`HRESULT` code. :class:`HRESULT`
1344 values contain information specifying whether the function call failed or
1345 succeeded, together with additional error code. If the return value signals a
1346 failure, an :class:`WindowsError` is automatically raised.
1349 .. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
1351 Windows only: Instances of this class represent loaded shared libraries,
1352 functions in these libraries use the ``stdcall`` calling convention, and are
1353 assumed to return :ctype:`int` by default.
1355 On Windows CE only the standard calling convention is used, for convenience the
1356 :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this
1359 The Python :term:`global interpreter lock` is released before calling any
1360 function exported by these libraries, and reacquired afterwards.
1363 .. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)
1365 Instances of this class behave like :class:`CDLL` instances, except that the
1366 Python GIL is *not* released during the function call, and after the function
1367 execution the Python error flag is checked. If the error flag is set, a Python
1368 exception is raised.
1370 Thus, this is only useful to call Python C api functions directly.
1372 All these classes can be instantiated by calling them with at least one
1373 argument, the pathname of the shared library. If you have an existing handle to
1374 an already loaded shared library, it can be passed as the ``handle`` named
1375 parameter, otherwise the underlying platforms ``dlopen`` or ``LoadLibrary``
1376 function is used to load the library into the process, and to get a handle to
1379 The *mode* parameter can be used to specify how the library is loaded. For
1380 details, consult the :manpage:`dlopen(3)` manpage, on Windows, *mode* is
1383 The *use_errno* parameter, when set to True, enables a ctypes mechanism that
1384 allows to access the system :data:`errno` error number in a safe way.
1385 :mod:`ctypes` maintains a thread-local copy of the systems :data:`errno`
1386 variable; if you call foreign functions created with ``use_errno=True`` then the
1387 :data:`errno` value before the function call is swapped with the ctypes private
1388 copy, the same happens immediately after the function call.
1390 The function :func:`ctypes.get_errno` returns the value of the ctypes private
1391 copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy
1392 to a new value and returns the former value.
1394 The *use_last_error* parameter, when set to True, enables the same mechanism for
1395 the Windows error code which is managed by the :func:`GetLastError` and
1396 :func:`SetLastError` Windows API functions; :func:`ctypes.get_last_error` and
1397 :func:`ctypes.set_last_error` are used to request and change the ctypes private
1398 copy of the windows error code.
1400 .. versionadded:: 2.6
1401 The *use_last_error* and *use_errno* optional parameters were added.
1403 .. data:: RTLD_GLOBAL
1406 Flag to use as *mode* parameter. On platforms where this flag is not available,
1407 it is defined as the integer zero.
1410 .. data:: RTLD_LOCAL
1413 Flag to use as *mode* parameter. On platforms where this is not available, it
1414 is the same as *RTLD_GLOBAL*.
1417 .. data:: DEFAULT_MODE
1420 The default mode which is used to load shared libraries. On OSX 10.3, this is
1421 *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*.
1423 Instances of these classes have no public methods, however :meth:`__getattr__`
1424 and :meth:`__getitem__` have special behavior: functions exported by the shared
1425 library can be accessed as attributes of by index. Please note that both
1426 :meth:`__getattr__` and :meth:`__getitem__` cache their result, so calling them
1427 repeatedly returns the same object each time.
1429 The following public attributes are available, their name starts with an
1430 underscore to not clash with exported function names:
1433 .. attribute:: PyDLL._handle
1435 The system handle used to access the library.
1438 .. attribute:: PyDLL._name
1440 The name of the library passed in the constructor.
1442 Shared libraries can also be loaded by using one of the prefabricated objects,
1443 which are instances of the :class:`LibraryLoader` class, either by calling the
1444 :meth:`LoadLibrary` method, or by retrieving the library as attribute of the
1448 .. class:: LibraryLoader(dlltype)
1450 Class which loads shared libraries. *dlltype* should be one of the
1451 :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types.
1453 :meth:`__getattr__` has special behavior: It allows to load a shared library by
1454 accessing it as attribute of a library loader instance. The result is cached,
1455 so repeated attribute accesses return the same library each time.
1458 .. method:: LoadLibrary(name)
1460 Load a shared library into the process and return it. This method always
1461 returns a new instance of the library.
1463 These prefabricated library loaders are available:
1469 Creates :class:`CDLL` instances.
1475 Windows only: Creates :class:`WinDLL` instances.
1481 Windows only: Creates :class:`OleDLL` instances.
1487 Creates :class:`PyDLL` instances.
1489 For accessing the C Python api directly, a ready-to-use Python shared library
1490 object is available:
1496 An instance of :class:`PyDLL` that exposes Python C API functions as
1497 attributes. Note that all these functions are assumed to return C
1498 :ctype:`int`, which is of course not always the truth, so you have to assign
1499 the correct :attr:`restype` attribute to use these functions.
1502 .. _ctypes-foreign-functions:
1507 As explained in the previous section, foreign functions can be accessed as
1508 attributes of loaded shared libraries. The function objects created in this way
1509 by default accept any number of arguments, accept any ctypes data instances as
1510 arguments, and return the default result type specified by the library loader.
1511 They are instances of a private class:
1516 Base class for C callable foreign functions.
1518 Instances of foreign functions are also C compatible data types; they
1519 represent C function pointers.
1521 This behavior can be customized by assigning to special attributes of the
1522 foreign function object.
1525 .. attribute:: restype
1527 Assign a ctypes type to specify the result type of the foreign function.
1528 Use ``None`` for :ctype:`void`, a function not returning anything.
1530 It is possible to assign a callable Python object that is not a ctypes
1531 type, in this case the function is assumed to return a C :ctype:`int`, and
1532 the callable will be called with this integer, allowing to do further
1533 processing or error checking. Using this is deprecated, for more flexible
1534 post processing or error checking use a ctypes data type as
1535 :attr:`restype` and assign a callable to the :attr:`errcheck` attribute.
1538 .. attribute:: argtypes
1540 Assign a tuple of ctypes types to specify the argument types that the
1541 function accepts. Functions using the ``stdcall`` calling convention can
1542 only be called with the same number of arguments as the length of this
1543 tuple; functions using the C calling convention accept additional,
1544 unspecified arguments as well.
1546 When a foreign function is called, each actual argument is passed to the
1547 :meth:`from_param` class method of the items in the :attr:`argtypes`
1548 tuple, this method allows to adapt the actual argument to an object that
1549 the foreign function accepts. For example, a :class:`c_char_p` item in
1550 the :attr:`argtypes` tuple will convert a unicode string passed as
1551 argument into an byte string using ctypes conversion rules.
1553 New: It is now possible to put items in argtypes which are not ctypes
1554 types, but each item must have a :meth:`from_param` method which returns a
1555 value usable as argument (integer, string, ctypes instance). This allows
1556 to define adapters that can adapt custom objects as function parameters.
1559 .. attribute:: errcheck
1561 Assign a Python function or another callable to this attribute. The
1562 callable will be called with three or more arguments:
1564 .. function:: callable(result, func, arguments)
1567 *result* is what the foreign function returns, as specified by the
1568 :attr:`restype` attribute.
1570 *func* is the foreign function object itself, this allows to reuse the
1571 same callable object to check or post process the results of several
1574 *arguments* is a tuple containing the parameters originally passed to
1575 the function call, this allows to specialize the behavior on the
1578 The object that this function returns will be returned from the
1579 foreign function call, but it can also check the result value
1580 and raise an exception if the foreign function call failed.
1583 .. exception:: ArgumentError()
1585 This exception is raised when a foreign function call cannot convert one of the
1589 .. _ctypes-function-prototypes:
1594 Foreign functions can also be created by instantiating function prototypes.
1595 Function prototypes are similar to function prototypes in C; they describe a
1596 function (return type, argument types, calling convention) without defining an
1597 implementation. The factory functions must be called with the desired result
1598 type and the argument types of the function.
1601 .. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
1603 The returned function prototype creates functions that use the standard C
1604 calling convention. The function will release the GIL during the call. If
1605 *use_errno* is set to True, the ctypes private copy of the system
1606 :data:`errno` variable is exchanged with the real :data:`errno` value before
1607 and after the call; *use_last_error* does the same for the Windows error
1610 .. versionchanged:: 2.6
1611 The optional *use_errno* and *use_last_error* parameters were added.
1614 .. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
1616 Windows only: The returned function prototype creates functions that use the
1617 ``stdcall`` calling convention, except on Windows CE where
1618 :func:`WINFUNCTYPE` is the same as :func:`CFUNCTYPE`. The function will
1619 release the GIL during the call. *use_errno* and *use_last_error* have the
1620 same meaning as above.
1623 .. function:: PYFUNCTYPE(restype, *argtypes)
1625 The returned function prototype creates functions that use the Python calling
1626 convention. The function will *not* release the GIL during the call.
1628 Function prototypes created by these factory functions can be instantiated in
1629 different ways, depending on the type and number of the parameters in the call:
1632 .. function:: prototype(address)
1636 Returns a foreign function at the specified address which must be an integer.
1639 .. function:: prototype(callable)
1643 Create a C callable function (a callback function) from a Python *callable*.
1646 .. function:: prototype(func_spec[, paramflags])
1650 Returns a foreign function exported by a shared library. *func_spec* must be a
1651 2-tuple ``(name_or_ordinal, library)``. The first item is the name of the
1652 exported function as string, or the ordinal of the exported function as small
1653 integer. The second item is the shared library instance.
1656 .. function:: prototype(vtbl_index, name[, paramflags[, iid]])
1660 Returns a foreign function that will call a COM method. *vtbl_index* is the
1661 index into the virtual function table, a small non-negative integer. *name* is
1662 name of the COM method. *iid* is an optional pointer to the interface identifier
1663 which is used in extended error reporting.
1665 COM methods use a special calling convention: They require a pointer to the COM
1666 interface as first argument, in addition to those parameters that are specified
1667 in the :attr:`argtypes` tuple.
1669 The optional *paramflags* parameter creates foreign function wrappers with much
1670 more functionality than the features described above.
1672 *paramflags* must be a tuple of the same length as :attr:`argtypes`.
1674 Each item in this tuple contains further information about a parameter, it must
1675 be a tuple containing one, two, or three items.
1677 The first item is an integer containing a combination of direction
1678 flags for the parameter:
1681 Specifies an input parameter to the function.
1684 Output parameter. The foreign function fills in a value.
1687 Input parameter which defaults to the integer zero.
1689 The optional second item is the parameter name as string. If this is specified,
1690 the foreign function can be called with named parameters.
1692 The optional third item is the default value for this parameter.
1694 This example demonstrates how to wrap the Windows ``MessageBoxA`` function so
1695 that it supports default parameters and named arguments. The C declaration from
1696 the windows header file is this::
1698 WINUSERAPI int WINAPI
1705 Here is the wrapping with :mod:`ctypes`::
1707 >>> from ctypes import c_int, WINFUNCTYPE, windll
1708 >>> from ctypes.wintypes import HWND, LPCSTR, UINT
1709 >>> prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
1710 >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
1711 >>> MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)
1714 The MessageBox foreign function can now be called in these ways::
1717 >>> MessageBox(text="Spam, spam, spam")
1718 >>> MessageBox(flags=2, text="foo bar")
1721 A second example demonstrates output parameters. The win32 ``GetWindowRect``
1722 function retrieves the dimensions of a specified window by copying them into
1723 ``RECT`` structure that the caller has to supply. Here is the C declaration::
1725 WINUSERAPI BOOL WINAPI
1730 Here is the wrapping with :mod:`ctypes`::
1732 >>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
1733 >>> from ctypes.wintypes import BOOL, HWND, RECT
1734 >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
1735 >>> paramflags = (1, "hwnd"), (2, "lprect")
1736 >>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
1739 Functions with output parameters will automatically return the output parameter
1740 value if there is a single one, or a tuple containing the output parameter
1741 values when there are more than one, so the GetWindowRect function now returns a
1742 RECT instance, when called.
1744 Output parameters can be combined with the :attr:`errcheck` protocol to do
1745 further output processing and error checking. The win32 ``GetWindowRect`` api
1746 function returns a ``BOOL`` to signal success or failure, so this function could
1747 do the error checking, and raises an exception when the api call failed::
1749 >>> def errcheck(result, func, args):
1751 ... raise WinError()
1754 >>> GetWindowRect.errcheck = errcheck
1757 If the :attr:`errcheck` function returns the argument tuple it receives
1758 unchanged, :mod:`ctypes` continues the normal processing it does on the output
1759 parameters. If you want to return a tuple of window coordinates instead of a
1760 ``RECT`` instance, you can retrieve the fields in the function and return them
1761 instead, the normal processing will no longer take place::
1763 >>> def errcheck(result, func, args):
1765 ... raise WinError()
1767 ... return rc.left, rc.top, rc.bottom, rc.right
1769 >>> GetWindowRect.errcheck = errcheck
1773 .. _ctypes-utility-functions:
1779 .. function:: addressof(obj)
1781 Returns the address of the memory buffer as integer. *obj* must be an
1782 instance of a ctypes type.
1785 .. function:: alignment(obj_or_type)
1787 Returns the alignment requirements of a ctypes type. *obj_or_type* must be a
1788 ctypes type or instance.
1791 .. function:: byref(obj[, offset])
1793 Returns a light-weight pointer to *obj*, which must be an instance of a
1794 ctypes type. *offset* defaults to zero, and must be an integer that will be
1795 added to the internal pointer value.
1797 ``byref(obj, offset)`` corresponds to this C code::
1799 (((char *)&obj) + offset)
1801 The returned object can only be used as a foreign function call
1802 parameter. It behaves similar to ``pointer(obj)``, but the
1803 construction is a lot faster.
1805 .. versionadded:: 2.6
1806 The *offset* optional argument was added.
1809 .. function:: cast(obj, type)
1811 This function is similar to the cast operator in C. It returns a new
1812 instance of *type* which points to the same memory block as *obj*. *type*
1813 must be a pointer type, and *obj* must be an object that can be interpreted
1817 .. function:: create_string_buffer(init_or_size[, size])
1819 This function creates a mutable character buffer. The returned object is a
1820 ctypes array of :class:`c_char`.
1822 *init_or_size* must be an integer which specifies the size of the array, or a
1823 string which will be used to initialize the array items.
1825 If a string is specified as first argument, the buffer is made one item larger
1826 than the length of the string so that the last element in the array is a NUL
1827 termination character. An integer can be passed as second argument which allows
1828 to specify the size of the array if the length of the string should not be used.
1830 If the first parameter is a unicode string, it is converted into an 8-bit string
1831 according to ctypes conversion rules.
1834 .. function:: create_unicode_buffer(init_or_size[, size])
1836 This function creates a mutable unicode character buffer. The returned object is
1837 a ctypes array of :class:`c_wchar`.
1839 *init_or_size* must be an integer which specifies the size of the array, or a
1840 unicode string which will be used to initialize the array items.
1842 If a unicode string is specified as first argument, the buffer is made one item
1843 larger than the length of the string so that the last element in the array is a
1844 NUL termination character. An integer can be passed as second argument which
1845 allows to specify the size of the array if the length of the string should not
1848 If the first parameter is a 8-bit string, it is converted into an unicode string
1849 according to ctypes conversion rules.
1852 .. function:: DllCanUnloadNow()
1854 Windows only: This function is a hook which allows to implement in-process
1855 COM servers with ctypes. It is called from the DllCanUnloadNow function that
1856 the _ctypes extension dll exports.
1859 .. function:: DllGetClassObject()
1861 Windows only: This function is a hook which allows to implement in-process
1862 COM servers with ctypes. It is called from the DllGetClassObject function
1863 that the ``_ctypes`` extension dll exports.
1866 .. function:: find_library(name)
1867 :module: ctypes.util
1869 Try to find a library and return a pathname. *name* is the library name
1870 without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version
1871 number (this is the form used for the posix linker option :option:`-l`). If
1872 no library can be found, returns ``None``.
1874 The exact functionality is system dependent.
1876 .. versionchanged:: 2.6
1877 Windows only: ``find_library("m")`` or ``find_library("c")`` return the
1878 result of a call to ``find_msvcrt()``.
1881 .. function:: find_msvcrt()
1882 :module: ctypes.util
1884 Windows only: return the filename of the VC runtype library used by Python,
1885 and by the extension modules. If the name of the library cannot be
1886 determined, ``None`` is returned.
1888 If you need to free memory, for example, allocated by an extension module
1889 with a call to the ``free(void *)``, it is important that you use the
1890 function in the same library that allocated the memory.
1892 .. versionadded:: 2.6
1895 .. function:: FormatError([code])
1897 Windows only: Returns a textual description of the error code *code*. If no
1898 error code is specified, the last error code is used by calling the Windows
1899 api function GetLastError.
1902 .. function:: GetLastError()
1904 Windows only: Returns the last error code set by Windows in the calling thread.
1905 This function calls the Windows `GetLastError()` function directly,
1906 it does not return the ctypes-private copy of the error code.
1908 .. function:: get_errno()
1910 Returns the current value of the ctypes-private copy of the system
1911 :data:`errno` variable in the calling thread.
1913 .. versionadded:: 2.6
1915 .. function:: get_last_error()
1917 Windows only: returns the current value of the ctypes-private copy of the system
1918 :data:`LastError` variable in the calling thread.
1920 .. versionadded:: 2.6
1922 .. function:: memmove(dst, src, count)
1924 Same as the standard C memmove library function: copies *count* bytes from
1925 *src* to *dst*. *dst* and *src* must be integers or ctypes instances that can
1926 be converted to pointers.
1929 .. function:: memset(dst, c, count)
1931 Same as the standard C memset library function: fills the memory block at
1932 address *dst* with *count* bytes of value *c*. *dst* must be an integer
1933 specifying an address, or a ctypes instance.
1936 .. function:: POINTER(type)
1938 This factory function creates and returns a new ctypes pointer type. Pointer
1939 types are cached an reused internally, so calling this function repeatedly is
1940 cheap. *type* must be a ctypes type.
1943 .. function:: pointer(obj)
1945 This function creates a new pointer instance, pointing to *obj*. The returned
1946 object is of the type ``POINTER(type(obj))``.
1948 Note: If you just want to pass a pointer to an object to a foreign function
1949 call, you should use ``byref(obj)`` which is much faster.
1952 .. function:: resize(obj, size)
1954 This function resizes the internal memory buffer of *obj*, which must be an
1955 instance of a ctypes type. It is not possible to make the buffer smaller
1956 than the native size of the objects type, as given by ``sizeof(type(obj))``,
1957 but it is possible to enlarge the buffer.
1960 .. function:: set_conversion_mode(encoding, errors)
1962 This function sets the rules that ctypes objects use when converting between
1963 8-bit strings and unicode strings. *encoding* must be a string specifying an
1964 encoding, like ``'utf-8'`` or ``'mbcs'``, *errors* must be a string
1965 specifying the error handling on encoding/decoding errors. Examples of
1966 possible values are ``"strict"``, ``"replace"``, or ``"ignore"``.
1968 :func:`set_conversion_mode` returns a 2-tuple containing the previous
1969 conversion rules. On windows, the initial conversion rules are ``('mbcs',
1970 'ignore')``, on other systems ``('ascii', 'strict')``.
1973 .. function:: set_errno(value)
1975 Set the current value of the ctypes-private copy of the system :data:`errno`
1976 variable in the calling thread to *value* and return the previous value.
1978 .. versionadded:: 2.6
1981 .. function:: set_last_error(value)
1983 Windows only: set the current value of the ctypes-private copy of the system
1984 :data:`LastError` variable in the calling thread to *value* and return the
1987 .. versionadded:: 2.6
1990 .. function:: sizeof(obj_or_type)
1992 Returns the size in bytes of a ctypes type or instance memory buffer. Does the
1993 same as the C ``sizeof()`` function.
1996 .. function:: string_at(address[, size])
1998 This function returns the string starting at memory address address. If size
1999 is specified, it is used as size, otherwise the string is assumed to be
2003 .. function:: WinError(code=None, descr=None)
2005 Windows only: this function is probably the worst-named thing in ctypes. It
2006 creates an instance of WindowsError. If *code* is not specified,
2007 ``GetLastError`` is called to determine the error code. If ``descr`` is not
2008 specified, :func:`FormatError` is called to get a textual description of the
2012 .. function:: wstring_at(address[, size])
2014 This function returns the wide character string starting at memory address
2015 *address* as unicode string. If *size* is specified, it is used as the
2016 number of characters of the string, otherwise the string is assumed to be
2020 .. _ctypes-data-types:
2028 This non-public class is the common base class of all ctypes data types.
2029 Among other things, all ctypes type instances contain a memory block that
2030 hold C compatible data; the address of the memory block is returned by the
2031 :func:`addressof` helper function. Another instance variable is exposed as
2032 :attr:`_objects`; this contains other Python objects that need to be kept
2033 alive in case the memory block contains pointers.
2035 Common methods of ctypes data types, these are all class methods (to be
2036 exact, they are methods of the :term:`metaclass`):
2039 .. method:: _CData.from_buffer(source[, offset])
2041 This method returns a ctypes instance that shares the buffer of the
2042 *source* object. The *source* object must support the writeable buffer
2043 interface. The optional *offset* parameter specifies an offset into the
2044 source buffer in bytes; the default is zero. If the source buffer is not
2045 large enough a :exc:`ValueError` is raised.
2047 .. versionadded:: 2.6
2050 .. method:: _CData.from_buffer_copy(source[, offset])
2052 This method creates a ctypes instance, copying the buffer from the
2053 *source* object buffer which must be readable. The optional *offset*
2054 parameter specifies an offset into the source buffer in bytes; the default
2055 is zero. If the source buffer is not large enough a :exc:`ValueError` is
2058 .. versionadded:: 2.6
2061 .. method:: from_address(address)
2063 This method returns a ctypes type instance using the memory specified by
2064 *address* which must be an integer.
2067 .. method:: from_param(obj)
2069 This method adapts *obj* to a ctypes type. It is called with the actual
2070 object used in a foreign function call when the type is present in the
2071 foreign function's :attr:`argtypes` tuple; it must return an object that
2072 can be used as a function call parameter.
2074 All ctypes data types have a default implementation of this classmethod
2075 that normally returns *obj* if that is an instance of the type. Some
2076 types accept other objects as well.
2079 .. method:: in_dll(library, name)
2081 This method returns a ctypes type instance exported by a shared
2082 library. *name* is the name of the symbol that exports the data, *library*
2083 is the loaded shared library.
2086 Common instance variables of ctypes data types:
2088 .. attribute:: _b_base_
2090 Sometimes ctypes data instances do not own the memory block they contain,
2091 instead they share part of the memory block of a base object. The
2092 :attr:`_b_base_` read-only member is the root ctypes object that owns the
2096 .. attribute:: _b_needsfree_
2098 This read-only variable is true when the ctypes data instance has
2099 allocated the memory block itself, false otherwise.
2102 .. attribute:: _objects
2104 This member is either ``None`` or a dictionary containing Python objects
2105 that need to be kept alive so that the memory block contents is kept
2106 valid. This object is only exposed for debugging; never modify the
2107 contents of this dictionary.
2110 .. _ctypes-fundamental-data-types-2:
2112 Fundamental data types
2113 ^^^^^^^^^^^^^^^^^^^^^^
2116 .. class:: _SimpleCData
2118 This non-public class is the base class of all fundamental ctypes data
2119 types. It is mentioned here because it contains the common attributes of the
2120 fundamental ctypes data types. :class:`_SimpleCData` is a subclass of
2121 :class:`_CData`, so it inherits their methods and attributes.
2123 .. versionchanged:: 2.6
2124 ctypes data types that are not and do not contain pointers can now be
2127 Instances have a single attribute:
2129 .. attribute:: value
2131 This attribute contains the actual value of the instance. For integer and
2132 pointer types, it is an integer, for character types, it is a single
2133 character string, for character pointer types it is a Python string or
2136 When the ``value`` attribute is retrieved from a ctypes instance, usually
2137 a new object is returned each time. :mod:`ctypes` does *not* implement
2138 original object return, always a new object is constructed. The same is
2139 true for all other ctypes object instances.
2142 Fundamental data types, when returned as foreign function call results, or, for
2143 example, by retrieving structure field members or array items, are transparently
2144 converted to native Python types. In other words, if a foreign function has a
2145 :attr:`restype` of :class:`c_char_p`, you will always receive a Python string,
2146 *not* a :class:`c_char_p` instance.
2148 Subclasses of fundamental data types do *not* inherit this behavior. So, if a
2149 foreign functions :attr:`restype` is a subclass of :class:`c_void_p`, you will
2150 receive an instance of this subclass from the function call. Of course, you can
2151 get the value of the pointer by accessing the ``value`` attribute.
2153 These are the fundamental ctypes data types:
2157 Represents the C :ctype:`signed char` datatype, and interprets the value as
2158 small integer. The constructor accepts an optional integer initializer; no
2159 overflow checking is done.
2164 Represents the C :ctype:`char` datatype, and interprets the value as a single
2165 character. The constructor accepts an optional string initializer, the
2166 length of the string must be exactly one character.
2171 Represents the C :ctype:`char *` datatype when it points to a zero-terminated
2172 string. For a general character pointer that may also point to binary data,
2173 ``POINTER(c_char)`` must be used. The constructor accepts an integer
2174 address, or a string.
2179 Represents the C :ctype:`double` datatype. The constructor accepts an
2180 optional float initializer.
2183 .. class:: c_longdouble
2185 Represents the C :ctype:`long double` datatype. The constructor accepts an
2186 optional float initializer. On platforms where ``sizeof(long double) ==
2187 sizeof(double)`` it is an alias to :class:`c_double`.
2189 .. versionadded:: 2.6
2193 Represents the C :ctype:`float` datatype. The constructor accepts an
2194 optional float initializer.
2199 Represents the C :ctype:`signed int` datatype. The constructor accepts an
2200 optional integer initializer; no overflow checking is done. On platforms
2201 where ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`.
2206 Represents the C 8-bit :ctype:`signed int` datatype. Usually an alias for
2212 Represents the C 16-bit :ctype:`signed int` datatype. Usually an alias for
2218 Represents the C 32-bit :ctype:`signed int` datatype. Usually an alias for
2224 Represents the C 64-bit :ctype:`signed int` datatype. Usually an alias for
2225 :class:`c_longlong`.
2230 Represents the C :ctype:`signed long` datatype. The constructor accepts an
2231 optional integer initializer; no overflow checking is done.
2234 .. class:: c_longlong
2236 Represents the C :ctype:`signed long long` datatype. The constructor accepts
2237 an optional integer initializer; no overflow checking is done.
2242 Represents the C :ctype:`signed short` datatype. The constructor accepts an
2243 optional integer initializer; no overflow checking is done.
2248 Represents the C :ctype:`size_t` datatype.
2253 Represents the C :ctype:`unsigned char` datatype, it interprets the value as
2254 small integer. The constructor accepts an optional integer initializer; no
2255 overflow checking is done.
2260 Represents the C :ctype:`unsigned int` datatype. The constructor accepts an
2261 optional integer initializer; no overflow checking is done. On platforms
2262 where ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`.
2267 Represents the C 8-bit :ctype:`unsigned int` datatype. Usually an alias for
2273 Represents the C 16-bit :ctype:`unsigned int` datatype. Usually an alias for
2279 Represents the C 32-bit :ctype:`unsigned int` datatype. Usually an alias for
2285 Represents the C 64-bit :ctype:`unsigned int` datatype. Usually an alias for
2286 :class:`c_ulonglong`.
2291 Represents the C :ctype:`unsigned long` datatype. The constructor accepts an
2292 optional integer initializer; no overflow checking is done.
2295 .. class:: c_ulonglong
2297 Represents the C :ctype:`unsigned long long` datatype. The constructor
2298 accepts an optional integer initializer; no overflow checking is done.
2303 Represents the C :ctype:`unsigned short` datatype. The constructor accepts
2304 an optional integer initializer; no overflow checking is done.
2309 Represents the C :ctype:`void *` type. The value is represented as integer.
2310 The constructor accepts an optional integer initializer.
2315 Represents the C :ctype:`wchar_t` datatype, and interprets the value as a
2316 single character unicode string. The constructor accepts an optional string
2317 initializer, the length of the string must be exactly one character.
2320 .. class:: c_wchar_p
2322 Represents the C :ctype:`wchar_t *` datatype, which must be a pointer to a
2323 zero-terminated wide character string. The constructor accepts an integer
2324 address, or a string.
2329 Represent the C :ctype:`bool` datatype (more accurately, :ctype:`_Bool` from
2330 C99). Its value can be True or False, and the constructor accepts any object
2331 that has a truth value.
2333 .. versionadded:: 2.6
2338 Windows only: Represents a :ctype:`HRESULT` value, which contains success or
2339 error information for a function or method call.
2342 .. class:: py_object
2344 Represents the C :ctype:`PyObject *` datatype. Calling this without an
2345 argument creates a ``NULL`` :ctype:`PyObject *` pointer.
2347 The :mod:`ctypes.wintypes` module provides quite some other Windows specific
2348 data types, for example :ctype:`HWND`, :ctype:`WPARAM`, or :ctype:`DWORD`. Some
2349 useful structures like :ctype:`MSG` or :ctype:`RECT` are also defined.
2352 .. _ctypes-structured-data-types:
2354 Structured data types
2355 ^^^^^^^^^^^^^^^^^^^^^
2358 .. class:: Union(*args, **kw)
2360 Abstract base class for unions in native byte order.
2363 .. class:: BigEndianStructure(*args, **kw)
2365 Abstract base class for structures in *big endian* byte order.
2368 .. class:: LittleEndianStructure(*args, **kw)
2370 Abstract base class for structures in *little endian* byte order.
2372 Structures with non-native byte order cannot contain pointer type fields, or any
2373 other data types containing pointer type fields.
2376 .. class:: Structure(*args, **kw)
2378 Abstract base class for structures in *native* byte order.
2380 Concrete structure and union types must be created by subclassing one of these
2381 types, and at least define a :attr:`_fields_` class variable. :mod:`ctypes` will
2382 create :term:`descriptor`\s which allow reading and writing the fields by direct
2383 attribute accesses. These are the
2386 .. attribute:: _fields_
2388 A sequence defining the structure fields. The items must be 2-tuples or
2389 3-tuples. The first item is the name of the field, the second item
2390 specifies the type of the field; it can be any ctypes data type.
2392 For integer type fields like :class:`c_int`, a third optional item can be
2393 given. It must be a small positive integer defining the bit width of the
2396 Field names must be unique within one structure or union. This is not
2397 checked, only one field can be accessed when names are repeated.
2399 It is possible to define the :attr:`_fields_` class variable *after* the
2400 class statement that defines the Structure subclass, this allows to create
2401 data types that directly or indirectly reference themselves::
2403 class List(Structure):
2405 List._fields_ = [("pnext", POINTER(List)),
2409 The :attr:`_fields_` class variable must, however, be defined before the
2410 type is first used (an instance is created, ``sizeof()`` is called on it,
2411 and so on). Later assignments to the :attr:`_fields_` class variable will
2412 raise an AttributeError.
2414 Structure and union subclass constructors accept both positional and named
2415 arguments. Positional arguments are used to initialize the fields in the
2416 same order as they appear in the :attr:`_fields_` definition, named
2417 arguments are used to initialize the fields with the corresponding name.
2419 It is possible to defined sub-subclasses of structure types, they inherit
2420 the fields of the base class plus the :attr:`_fields_` defined in the
2421 sub-subclass, if any.
2424 .. attribute:: _pack_
2426 An optional small integer that allows to override the alignment of
2427 structure fields in the instance. :attr:`_pack_` must already be defined
2428 when :attr:`_fields_` is assigned, otherwise it will have no effect.
2431 .. attribute:: _anonymous_
2433 An optional sequence that lists the names of unnamed (anonymous) fields.
2434 :attr:`_anonymous_` must be already defined when :attr:`_fields_` is
2435 assigned, otherwise it will have no effect.
2437 The fields listed in this variable must be structure or union type fields.
2438 :mod:`ctypes` will create descriptors in the structure type that allows to
2439 access the nested fields directly, without the need to create the
2440 structure or union field.
2442 Here is an example type (Windows)::
2445 _fields_ = [("lptdesc", POINTER(TYPEDESC)),
2446 ("lpadesc", POINTER(ARRAYDESC)),
2447 ("hreftype", HREFTYPE)]
2449 class TYPEDESC(Structure):
2450 _anonymous_ = ("u",)
2451 _fields_ = [("u", _U),
2455 The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field
2456 specifies which one of the union fields is valid. Since the ``u`` field
2457 is defined as anonymous field, it is now possible to access the members
2458 directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc``
2459 are equivalent, but the former is faster since it does not need to create
2460 a temporary union instance::
2464 td.lptdesc = POINTER(some_type)
2465 td.u.lptdesc = POINTER(some_type)
2467 It is possible to defined sub-subclasses of structures, they inherit the
2468 fields of the base class. If the subclass definition has a separate
2469 :attr:`_fields_` variable, the fields specified in this are appended to the
2470 fields of the base class.
2472 Structure and union constructors accept both positional and keyword
2473 arguments. Positional arguments are used to initialize member fields in the
2474 same order as they are appear in :attr:`_fields_`. Keyword arguments in the
2475 constructor are interpreted as attribute assignments, so they will initialize
2476 :attr:`_fields_` with the same name, or create new attributes for names not
2477 present in :attr:`_fields_`.
2480 .. _ctypes-arrays-pointers:
2485 Not yet written - please see the sections :ref:`ctypes-pointers` and section
2486 :ref:`ctypes-arrays` in the tutorial.