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 ``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 ``doctest`` to make sure that they
22 actually work. Since some code samples behave differently under Linux, Windows,
23 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 ``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 :class:`HRESULT` error code. The error
44 code is used to automatically raise a :class:`WindowsError` exception when
45 the function call fails.
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 ``getattr``
116 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 ``ctypes`` tries to protect you from calling functions with the wrong number of
156 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, ``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 ``ctypes``, so you should
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 (``char *`` or
205 ``wchar_t *``). Python integers and Python longs are passed as the platforms
206 default C ``int`` type, their value is masked to fit into the C type.
208 Before we move on calling functions with other parameter types, we have to learn
209 more about ``ctypes`` data types.
212 .. _ctypes-fundamental-data-types:
214 Fundamental data types
215 ^^^^^^^^^^^^^^^^^^^^^^
217 ``ctypes`` defines a number of primitive C compatible data types :
219 +----------------------+--------------------------------+----------------------------+
220 | ctypes type | C type | Python type |
221 +======================+================================+============================+
222 | :class:`c_char` | ``char`` | 1-character string |
223 +----------------------+--------------------------------+----------------------------+
224 | :class:`c_wchar` | ``wchar_t`` | 1-character unicode string |
225 +----------------------+--------------------------------+----------------------------+
226 | :class:`c_byte` | ``char`` | int/long |
227 +----------------------+--------------------------------+----------------------------+
228 | :class:`c_ubyte` | ``unsigned char`` | int/long |
229 +----------------------+--------------------------------+----------------------------+
230 | :class:`c_short` | ``short`` | int/long |
231 +----------------------+--------------------------------+----------------------------+
232 | :class:`c_ushort` | ``unsigned short`` | int/long |
233 +----------------------+--------------------------------+----------------------------+
234 | :class:`c_int` | ``int`` | int/long |
235 +----------------------+--------------------------------+----------------------------+
236 | :class:`c_uint` | ``unsigned int`` | int/long |
237 +----------------------+--------------------------------+----------------------------+
238 | :class:`c_long` | ``long`` | int/long |
239 +----------------------+--------------------------------+----------------------------+
240 | :class:`c_ulong` | ``unsigned long`` | int/long |
241 +----------------------+--------------------------------+----------------------------+
242 | :class:`c_longlong` | ``__int64`` or ``long long`` | int/long |
243 +----------------------+--------------------------------+----------------------------+
244 | :class:`c_ulonglong` | ``unsigned __int64`` or | int/long |
245 | | ``unsigned long long`` | |
246 +----------------------+--------------------------------+----------------------------+
247 | :class:`c_float` | ``float`` | float |
248 +----------------------+--------------------------------+----------------------------+
249 | :class:`c_double` | ``double`` | float |
250 +----------------------+--------------------------------+----------------------------+
251 | :class:`c_longdouble`| ``long double`` | float |
252 +----------------------+--------------------------------+----------------------------+
253 | :class:`c_char_p` | ``char *`` (NUL terminated) | string or ``None`` |
254 +----------------------+--------------------------------+----------------------------+
255 | :class:`c_wchar_p` | ``wchar_t *`` (NUL terminated) | unicode or ``None`` |
256 +----------------------+--------------------------------+----------------------------+
257 | :class:`c_void_p` | ``void *`` | int/long or ``None`` |
258 +----------------------+--------------------------------+----------------------------+
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 ``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 ``create_string_buffer`` function replaces the ``c_buffer`` function (which
325 is still available as an alias), as well as the ``c_string`` function from
326 earlier ctypes releases. To create a mutable memory block containing unicode
327 characters of the C type ``wchar_t`` use the ``create_unicode_buffer`` function.
330 .. _ctypes-calling-functions-continued:
332 Calling functions, continued
333 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
335 Note that printf prints to the real standard output channel, *not* to
336 ``sys.stdout``, so these examples will only work at the console prompt, not from
337 within *IDLE* or *PythonWin*::
339 >>> printf = libc.printf
340 >>> printf("Hello, %s\n", "World!")
343 >>> printf("Hello, %S\n", u"World!")
346 >>> printf("%d bottles of beer\n", 42)
349 >>> printf("%f bottles of beer\n", 42.5)
350 Traceback (most recent call last):
351 File "<stdin>", line 1, in ?
352 ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2
355 As has been mentioned before, all Python types except integers, strings, and
356 unicode strings have to be wrapped in their corresponding ``ctypes`` type, so
357 that they can be converted to the required C data type::
359 >>> printf("An int %d, a double %f\n", 1234, c_double(3.14))
360 An int 1234, a double 3.140000
365 .. _ctypes-calling-functions-with-own-custom-data-types:
367 Calling functions with your own custom data types
368 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
370 You can also customize ``ctypes`` argument conversion to allow instances of your
371 own classes be used as function arguments. ``ctypes`` looks for an
372 :attr:`_as_parameter_` attribute and uses this as the function argument. Of
373 course, it must be one of integer, string, or unicode::
375 >>> class Bottles(object):
376 ... def __init__(self, number):
377 ... self._as_parameter_ = number
379 >>> bottles = Bottles(42)
380 >>> printf("%d bottles of beer\n", bottles)
385 If you don't want to store the instance's data in the :attr:`_as_parameter_`
386 instance variable, you could define a ``property`` which makes the data
390 .. _ctypes-specifying-required-argument-types:
392 Specifying the required argument types (function prototypes)
393 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
395 It is possible to specify the required argument types of functions exported from
396 DLLs by setting the :attr:`argtypes` attribute.
398 :attr:`argtypes` must be a sequence of C data types (the ``printf`` function is
399 probably not a good example here, because it takes a variable number and
400 different types of parameters depending on the format string, on the other hand
401 this is quite handy to experiment with this feature)::
403 >>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
404 >>> printf("String '%s', Int %d, Double %f\n", "Hi", 10, 2.2)
405 String 'Hi', Int 10, Double 2.200000
409 Specifying a format protects against incompatible argument types (just as a
410 prototype for a C function), and tries to convert the arguments to valid types::
412 >>> printf("%d %d %d", 1, 2, 3)
413 Traceback (most recent call last):
414 File "<stdin>", line 1, in ?
415 ArgumentError: argument 2: exceptions.TypeError: wrong type
416 >>> printf("%s %d %f\n", "X", 2, 3)
421 If you have defined your own classes which you pass to function calls, you have
422 to implement a :meth:`from_param` class method for them to be able to use them
423 in the :attr:`argtypes` sequence. The :meth:`from_param` class method receives
424 the Python object passed to the function call, it should do a typecheck or
425 whatever is needed to make sure this object is acceptable, and then return the
426 object itself, its :attr:`_as_parameter_` attribute, or whatever you want to
427 pass as the C function argument in this case. Again, the result should be an
428 integer, string, unicode, a ``ctypes`` instance, or an object with an
429 :attr:`_as_parameter_` attribute.
432 .. _ctypes-return-types:
437 By default functions are assumed to return the C ``int`` type. Other return
438 types can be specified by setting the :attr:`restype` attribute of the function
441 Here is a more advanced example, it uses the ``strchr`` function, which expects
442 a string pointer and a char, and returns a pointer to a string::
444 >>> strchr = libc.strchr
445 >>> strchr("abcdef", ord("d")) # doctest: +SKIP
447 >>> strchr.restype = c_char_p # c_char_p is a pointer to a string
448 >>> strchr("abcdef", ord("d"))
450 >>> print strchr("abcdef", ord("x"))
454 If you want to avoid the ``ord("x")`` calls above, you can set the
455 :attr:`argtypes` attribute, and the second argument will be converted from a
456 single character Python string into a C char::
458 >>> strchr.restype = c_char_p
459 >>> strchr.argtypes = [c_char_p, c_char]
460 >>> strchr("abcdef", "d")
462 >>> strchr("abcdef", "def")
463 Traceback (most recent call last):
464 File "<stdin>", line 1, in ?
465 ArgumentError: argument 2: exceptions.TypeError: one character string expected
466 >>> print strchr("abcdef", "x")
468 >>> strchr("abcdef", "d")
472 You can also use a callable Python object (a function or a class for example) as
473 the :attr:`restype` attribute, if the foreign function returns an integer. The
474 callable will be called with the ``integer`` the C function returns, and the
475 result of this call will be used as the result of your function call. This is
476 useful to check for error return values and automatically raise an exception::
478 >>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
479 >>> def ValidHandle(value):
485 >>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS
486 >>> GetModuleHandle(None) # doctest: +WINDOWS
488 >>> GetModuleHandle("something silly") # doctest: +WINDOWS
489 Traceback (most recent call last):
490 File "<stdin>", line 1, in ?
491 File "<stdin>", line 3, in ValidHandle
492 WindowsError: [Errno 126] The specified module could not be found.
495 ``WinError`` is a function which will call Windows ``FormatMessage()`` api to
496 get the string representation of an error code, and *returns* an exception.
497 ``WinError`` takes an optional error code parameter, if no one is used, it calls
498 :func:`GetLastError` to retrieve it.
500 Please note that a much more powerful error checking mechanism is available
501 through the :attr:`errcheck` attribute; see the reference manual for details.
504 .. _ctypes-passing-pointers:
506 Passing pointers (or: passing parameters by reference)
507 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
509 Sometimes a C api function expects a *pointer* to a data type as parameter,
510 probably to write into the corresponding location, or if the data is too large
511 to be passed by value. This is also known as *passing parameters by reference*.
513 ``ctypes`` exports the :func:`byref` function which is used to pass parameters
514 by reference. The same effect can be achieved with the ``pointer`` function,
515 although ``pointer`` does a lot more work since it constructs a real pointer
516 object, so it is faster to use :func:`byref` if you don't need the pointer
517 object in Python itself::
521 >>> s = create_string_buffer('\000' * 32)
522 >>> print i.value, f.value, repr(s.value)
524 >>> libc.sscanf("1 3.14 Hello", "%d %f %s",
525 ... byref(i), byref(f), s)
527 >>> print i.value, f.value, repr(s.value)
528 1 3.1400001049 'Hello'
532 .. _ctypes-structures-unions:
534 Structures and unions
535 ^^^^^^^^^^^^^^^^^^^^^
537 Structures and unions must derive from the :class:`Structure` and :class:`Union`
538 base classes which are defined in the ``ctypes`` module. Each subclass must
539 define a :attr:`_fields_` attribute. :attr:`_fields_` must be a list of
540 *2-tuples*, containing a *field name* and a *field type*.
542 The field type must be a ``ctypes`` type like :class:`c_int`, or any other
543 derived ``ctypes`` type: structure, union, array, pointer.
545 Here is a simple example of a POINT structure, which contains two integers named
546 ``x`` and ``y``, and also shows how to initialize a structure in the
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 ``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 BigEndianStructure, LittleEndianStructure, BigEndianUnion, and LittleEndianUnion
612 base classes. These classes cannot contain pointer fields.
615 .. _ctypes-bit-fields-in-structures-unions:
617 Bit fields in structures and unions
618 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
620 It is possible to create structures and unions containing bit fields. Bit fields
621 are only possible for integer fields, the bit width is specified as the third
622 item in the :attr:`_fields_` tuples::
624 >>> class Int(Structure):
625 ... _fields_ = [("first_16", c_int, 16),
626 ... ("second_16", c_int, 16)]
628 >>> print Int.first_16
629 <Field type=c_long, ofs=0:0, bits=16>
630 >>> print Int.second_16
631 <Field type=c_long, ofs=0:16, bits=16>
640 Arrays are sequences, containing a fixed number of instances of the same type.
642 The recommended way to create array types is by multiplying a data type with a
645 TenPointsArrayType = POINT * 10
647 Here is an example of an somewhat artificial data type, a structure containing 4
648 POINTs among other stuff::
650 >>> from ctypes import *
651 >>> class POINT(Structure):
652 ... _fields_ = ("x", c_int), ("y", c_int)
654 >>> class MyStruct(Structure):
655 ... _fields_ = [("a", c_int),
657 ... ("point_array", POINT * 4)]
659 >>> print len(MyStruct().point_array)
663 Instances are created in the usual way, by calling the class::
665 arr = TenPointsArrayType()
669 The above code print a series of ``0 0`` lines, because the array contents is
670 initialized to zeros.
672 Initializers of the correct type can also be specified::
674 >>> from ctypes import *
675 >>> TenIntegers = c_int * 10
676 >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
678 <c_long_Array_10 object at 0x...>
679 >>> for i in ii: print i,
690 Pointer instances are created by calling the ``pointer`` function on a
693 >>> from ctypes import *
698 Pointer instances have a ``contents`` attribute which returns the object to
699 which the pointer points, the ``i`` object above::
705 Note that ``ctypes`` does not have OOR (original object return), it constructs a
706 new, equivalent object each time you retrieve an attribute::
710 >>> pi.contents is pi.contents
714 Assigning another :class:`c_int` instance to the pointer's contents attribute
715 would cause the pointer to point to the memory location where this is stored::
723 .. XXX Document dereferencing pointers, and that it is preferred over the .contents attribute.
725 Pointer instances can also be indexed with integers::
731 Assigning to an integer index changes the pointed to value::
740 It is also possible to use indexes different from 0, but you must know what
741 you're doing, just as in C: You can access or change arbitrary memory locations.
742 Generally you only use this feature if you receive a pointer from a C function,
743 and you *know* that the pointer actually points to an array instead of a single
746 Behind the scenes, the ``pointer`` function does more than simply create pointer
747 instances, it has to create pointer *types* first. This is done with the
748 ``POINTER`` function, which accepts any ``ctypes`` type, and returns a new
751 >>> PI = POINTER(c_int)
753 <class 'ctypes.LP_c_long'>
755 Traceback (most recent call last):
756 File "<stdin>", line 1, in ?
757 TypeError: expected c_long instead of int
759 <ctypes.LP_c_long object at 0x...>
762 Calling the pointer type without an argument creates a ``NULL`` pointer.
763 ``NULL`` pointers have a ``False`` boolean value::
765 >>> null_ptr = POINTER(c_int)()
766 >>> print bool(null_ptr)
770 ``ctypes`` checks for ``NULL`` when dereferencing pointers (but dereferencing
771 invalid non-\ ``NULL`` pointers would crash Python)::
774 Traceback (most recent call last):
776 ValueError: NULL pointer access
779 >>> null_ptr[0] = 1234
780 Traceback (most recent call last):
782 ValueError: NULL pointer access
786 .. _ctypes-type-conversions:
791 Usually, ctypes does strict type checking. This means, if you have
792 ``POINTER(c_int)`` in the :attr:`argtypes` list of a function or as the type of
793 a member field in a structure definition, only instances of exactly the same
794 type are accepted. There are some exceptions to this rule, where ctypes accepts
795 other objects. For example, you can pass compatible array instances instead of
796 pointer types. So, for ``POINTER(c_int)``, ctypes accepts an array of c_int::
798 >>> class Bar(Structure):
799 ... _fields_ = [("count", c_int), ("values", POINTER(c_int))]
802 >>> bar.values = (c_int * 3)(1, 2, 3)
804 >>> for i in range(bar.count):
805 ... print bar.values[i]
812 To set a POINTER type field to ``NULL``, you can assign ``None``::
814 >>> bar.values = None
817 .. XXX list other conversions...
819 Sometimes you have instances of incompatible types. In C, you can cast one
820 type into another type. ``ctypes`` provides a ``cast`` function which can be
821 used in the same way. The ``Bar`` structure defined above accepts
822 ``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field,
823 but not instances of other types::
825 >>> bar.values = (c_byte * 4)()
826 Traceback (most recent call last):
827 File "<stdin>", line 1, in ?
828 TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
831 For these cases, the ``cast`` function is handy.
833 The ``cast`` function can be used to cast a ctypes instance into a pointer to a
834 different ctypes data type. ``cast`` takes two parameters, a ctypes object that
835 is or can be converted to a pointer of some kind, and a ctypes pointer type. It
836 returns an instance of the second argument, which references the same memory
837 block as the first argument::
839 >>> a = (c_byte * 4)()
840 >>> cast(a, POINTER(c_int))
841 <ctypes.LP_c_long object at ...>
844 So, ``cast`` can be used to assign to the ``values`` field of ``Bar`` the
848 >>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
849 >>> print bar.values[0]
854 .. _ctypes-incomplete-types:
859 *Incomplete Types* are structures, unions or arrays whose members are not yet
860 specified. In C, they are specified by forward declarations, which are defined
863 struct cell; /* forward declaration */
870 The straightforward translation into ctypes code would be this, but it does not
873 >>> class cell(Structure):
874 ... _fields_ = [("name", c_char_p),
875 ... ("next", POINTER(cell))]
877 Traceback (most recent call last):
878 File "<stdin>", line 1, in ?
879 File "<stdin>", line 2, in cell
880 NameError: name 'cell' is not defined
883 because the new ``class cell`` is not available in the class statement itself.
884 In ``ctypes``, we can define the ``cell`` class and set the :attr:`_fields_`
885 attribute later, after the class statement::
887 >>> from ctypes import *
888 >>> class cell(Structure):
891 >>> cell._fields_ = [("name", c_char_p),
892 ... ("next", POINTER(cell))]
895 Lets try it. We create two instances of ``cell``, and let them point to each
896 other, and finally follow the pointer chain a few times::
902 >>> c1.next = pointer(c2)
903 >>> c2.next = pointer(c1)
905 >>> for i in range(8):
909 foo bar foo bar foo bar foo bar
913 .. _ctypes-callback-functions:
918 ``ctypes`` allows to create C callable function pointers from Python callables.
919 These are sometimes called *callback functions*.
921 First, you must create a class for the callback function, the class knows the
922 calling convention, the return type, and the number and types of arguments this
923 function will receive.
925 The CFUNCTYPE factory function creates types for callback functions using the
926 normal cdecl calling convention, and, on Windows, the WINFUNCTYPE factory
927 function creates types for callback functions using the stdcall calling
930 Both of these factory functions are called with the result type as first
931 argument, and the callback functions expected argument types as the remaining
934 I will present an example here which uses the standard C library's :func:`qsort`
935 function, this is used to sort items with the help of a callback function.
936 :func:`qsort` will be used to sort an array of integers::
938 >>> IntArray5 = c_int * 5
939 >>> ia = IntArray5(5, 1, 7, 33, 99)
940 >>> qsort = libc.qsort
941 >>> qsort.restype = None
944 :func:`qsort` must be called with a pointer to the data to sort, the number of
945 items in the data array, the size of one item, and a pointer to the comparison
946 function, the callback. The callback will then be called with two pointers to
947 items, and it must return a negative integer if the first item is smaller than
948 the second, a zero if they are equal, and a positive integer else.
950 So our callback function receives pointers to integers, and must return an
951 integer. First we create the ``type`` for the callback function::
953 >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
956 For the first implementation of the callback function, we simply print the
957 arguments we get, and return 0 (incremental development ;-)::
959 >>> def py_cmp_func(a, b):
960 ... print "py_cmp_func", a, b
965 Create the C callable callback::
967 >>> cmp_func = CMPFUNC(py_cmp_func)
970 And we're ready to go::
972 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
973 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
974 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
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...>
985 We know how to access the contents of a pointer, so lets redefine our callback::
987 >>> def py_cmp_func(a, b):
988 ... print "py_cmp_func", a[0], b[0]
991 >>> cmp_func = CMPFUNC(py_cmp_func)
994 Here is what we get on Windows::
996 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
1009 It is funny to see that on linux the sort function seems to work much more
1010 efficient, it is doing less comparisons::
1012 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX
1020 Ah, we're nearly done! The last step is to actually compare the two items and
1021 return a useful result::
1023 >>> def py_cmp_func(a, b):
1024 ... print "py_cmp_func", a[0], b[0]
1025 ... return a[0] - b[0]
1029 Final run on Windows::
1031 >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +WINDOWS
1046 >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX
1054 It is quite interesting to see that the Windows :func:`qsort` function needs
1055 more comparisons than the linux version!
1057 As we can easily check, our array is sorted now::
1059 >>> for i in ia: print i,
1064 **Important note for callback functions:**
1066 Make sure you keep references to CFUNCTYPE objects as long as they are used from
1067 C code. ``ctypes`` doesn't, and if you don't, they may be garbage collected,
1068 crashing your program when a callback is made.
1071 .. _ctypes-accessing-values-exported-from-dlls:
1073 Accessing values exported from dlls
1074 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1076 Some shared libraries not only export functions, they also export variables. An
1077 example in the Python library itself is the ``Py_OptimizeFlag``, an integer set
1078 to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on
1081 ``ctypes`` can access values like this with the :meth:`in_dll` class methods of
1082 the type. *pythonapi* is a predefined symbol giving access to the Python C
1085 >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
1090 If the interpreter would have been started with :option:`-O`, the sample would
1091 have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been
1094 An extended example which also demonstrates the use of pointers accesses the
1095 ``PyImport_FrozenModules`` pointer exported by Python.
1097 Quoting the Python docs: *This pointer is initialized to point to an array of
1098 "struct _frozen" records, terminated by one whose members are all NULL or zero.
1099 When a frozen module is imported, it is searched in this table. Third-party code
1100 could play tricks with this to provide a dynamically created collection of
1103 So manipulating this pointer could even prove useful. To restrict the example
1104 size, we show only how this table can be read with ``ctypes``::
1106 >>> from ctypes import *
1108 >>> class struct_frozen(Structure):
1109 ... _fields_ = [("name", c_char_p),
1110 ... ("code", POINTER(c_ubyte)),
1111 ... ("size", c_int)]
1115 We have defined the ``struct _frozen`` data type, so we can get the pointer to
1118 >>> FrozenTable = POINTER(struct_frozen)
1119 >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
1122 Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we
1123 can iterate over it, but we just have to make sure that our loop terminates,
1124 because pointers have no size. Sooner or later it would probably crash with an
1125 access violation or whatever, so it's better to break out of the loop when we
1126 hit the NULL entry::
1128 >>> for item in table:
1129 ... print item.name, item.size
1130 ... if item.name is None:
1139 The fact that standard Python has a frozen module and a frozen package
1140 (indicated by the negative size member) is not well known, it is only used for
1141 testing. Try it out with ``import __hello__`` for example.
1144 .. _ctypes-surprises:
1149 There are some edges in ``ctypes`` where you may be expect something else than
1150 what actually happens.
1152 Consider the following example::
1154 >>> from ctypes import *
1155 >>> class POINT(Structure):
1156 ... _fields_ = ("x", c_int), ("y", c_int)
1158 >>> class RECT(Structure):
1159 ... _fields_ = ("a", POINT), ("b", POINT)
1161 >>> p1 = POINT(1, 2)
1162 >>> p2 = POINT(3, 4)
1163 >>> rc = RECT(p1, p2)
1164 >>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
1166 >>> # now swap the two points
1167 >>> rc.a, rc.b = rc.b, rc.a
1168 >>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
1172 Hm. We certainly expected the last statement to print ``3 4 1 2``. What
1173 happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
1175 >>> temp0, temp1 = rc.b, rc.a
1180 Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of
1181 the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer
1182 contents of ``temp0`` into ``rc`` 's buffer. This, in turn, changes the
1183 contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have
1184 the expected effect.
1186 Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
1187 doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing
1188 the root-object's underlying buffer.
1190 Another example that may behave different from what one would expect is this::
1193 >>> s.value = "abc def ghi"
1196 >>> s.value is s.value
1200 Why is it printing ``False``? ctypes instances are objects containing a memory
1201 block plus some :term:`descriptor`\s accessing the contents of the memory.
1202 Storing a Python object in the memory block does not store the object itself,
1203 instead the ``contents`` of the object is stored. Accessing the contents again
1204 constructs a new Python object each time!
1207 .. _ctypes-variable-sized-data-types:
1209 Variable-sized data types
1210 ^^^^^^^^^^^^^^^^^^^^^^^^^
1212 ``ctypes`` provides some support for variable-sized arrays and structures.
1214 The ``resize`` function can be used to resize the memory buffer of an existing
1215 ctypes object. The function takes the object as first argument, and the
1216 requested size in bytes as the second argument. The memory block cannot be made
1217 smaller than the natural memory block specified by the objects type, a
1218 ``ValueError`` is raised if this is tried::
1220 >>> short_array = (c_short * 4)()
1221 >>> print sizeof(short_array)
1223 >>> resize(short_array, 4)
1224 Traceback (most recent call last):
1226 ValueError: minimum size is 8
1227 >>> resize(short_array, 32)
1228 >>> sizeof(short_array)
1230 >>> sizeof(type(short_array))
1234 This is nice and fine, but how would one access the additional elements
1235 contained in this array? Since the type still only knows about 4 elements, we
1236 get errors accessing other elements::
1241 Traceback (most recent call last):
1243 IndexError: invalid index
1246 Another way to use variable-sized data types with ``ctypes`` is to use the
1247 dynamic nature of Python, and (re-)define the data type after the required size
1248 is already known, on a case by case basis.
1251 .. _ctypes-ctypes-reference:
1257 .. _ctypes-finding-shared-libraries:
1259 Finding shared libraries
1260 ^^^^^^^^^^^^^^^^^^^^^^^^
1262 When programming in a compiled language, shared libraries are accessed when
1263 compiling/linking a program, and when the program is run.
1265 The purpose of the ``find_library`` function is to locate a library in a way
1266 similar to what the compiler does (on platforms with several versions of a
1267 shared library the most recent should be loaded), while the ctypes library
1268 loaders act like when a program is run, and call the runtime loader directly.
1270 The ``ctypes.util`` module provides a function which can help to determine the
1274 .. data:: find_library(name)
1275 :module: ctypes.util
1278 Try to find a library and return a pathname. *name* is the library name without
1279 any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this
1280 is the form used for the posix linker option :option:`-l`). If no library can
1281 be found, returns ``None``.
1283 The exact functionality is system dependent.
1285 On Linux, ``find_library`` tries to run external programs (/sbin/ldconfig, gcc,
1286 and objdump) to find the library file. It returns the filename of the library
1287 file. Here are some examples::
1289 >>> from ctypes.util import find_library
1290 >>> find_library("m")
1292 >>> find_library("c")
1294 >>> find_library("bz2")
1298 On OS X, ``find_library`` tries several predefined naming schemes and paths to
1299 locate the library, and returns a full pathname if successful::
1301 >>> from ctypes.util import find_library
1302 >>> find_library("c")
1303 '/usr/lib/libc.dylib'
1304 >>> find_library("m")
1305 '/usr/lib/libm.dylib'
1306 >>> find_library("bz2")
1307 '/usr/lib/libbz2.dylib'
1308 >>> find_library("AGL")
1309 '/System/Library/Frameworks/AGL.framework/AGL'
1312 On Windows, ``find_library`` searches along the system search path, and returns
1313 the full pathname, but since there is no predefined naming scheme a call like
1314 ``find_library("c")`` will fail and return ``None``.
1316 If wrapping a shared library with ``ctypes``, it *may* be better to determine
1317 the shared library name at development type, and hardcode that into the wrapper
1318 module instead of using ``find_library`` to locate the library at runtime.
1321 .. _ctypes-loading-shared-libraries:
1323 Loading shared libraries
1324 ^^^^^^^^^^^^^^^^^^^^^^^^
1326 There are several ways to loaded shared libraries into the Python process. One
1327 way is to instantiate one of the following classes:
1330 .. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
1332 Instances of this class represent loaded shared libraries. Functions in these
1333 libraries use the standard C calling convention, and are assumed to return
1337 .. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
1339 Windows only: Instances of this class represent loaded shared libraries,
1340 functions in these libraries use the ``stdcall`` calling convention, and are
1341 assumed to return the windows specific :class:`HRESULT` code. :class:`HRESULT`
1342 values contain information specifying whether the function call failed or
1343 succeeded, together with additional error code. If the return value signals a
1344 failure, an :class:`WindowsError` is automatically raised.
1347 .. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
1349 Windows only: Instances of this class represent loaded shared libraries,
1350 functions in these libraries use the ``stdcall`` calling convention, and are
1351 assumed to return ``int`` by default.
1353 On Windows CE only the standard calling convention is used, for convenience the
1354 :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this
1357 The Python :term:`global interpreter lock` is released before calling any
1358 function exported by these libraries, and reacquired afterwards.
1361 .. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)
1363 Instances of this class behave like :class:`CDLL` instances, except that the
1364 Python GIL is *not* released during the function call, and after the function
1365 execution the Python error flag is checked. If the error flag is set, a Python
1366 exception is raised.
1368 Thus, this is only useful to call Python C api functions directly.
1370 All these classes can be instantiated by calling them with at least one
1371 argument, the pathname of the shared library. If you have an existing handle to
1372 an already loaded shared library, it can be passed as the ``handle`` named
1373 parameter, otherwise the underlying platforms ``dlopen`` or :meth:`LoadLibrary`
1374 function is used to load the library into the process, and to get a handle to
1377 The *mode* parameter can be used to specify how the library is loaded. For
1378 details, consult the ``dlopen(3)`` manpage, on Windows, *mode* is ignored.
1380 The *use_errno* parameter, when set to True, enables a ctypes mechanism that
1381 allows to access the system :data:`errno` error number in a safe way.
1382 :mod:`ctypes` maintains a thread-local copy of the systems :data:`errno`
1383 variable; if you call foreign functions created with ``use_errno=True`` then the
1384 :data:`errno` value before the function call is swapped with the ctypes private
1385 copy, the same happens immediately after the function call.
1387 The function :func:`ctypes.get_errno` returns the value of the ctypes private
1388 copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy
1389 to a new value and returns the former value.
1391 The *use_last_error* parameter, when set to True, enables the same mechanism for
1392 the Windows error code which is managed by the :func:`GetLastError` and
1393 :func:`SetLastError` Windows API functions; :func:`ctypes.get_last_error` and
1394 :func:`ctypes.set_last_error` are used to request and change the ctypes private
1395 copy of the windows error code.
1397 .. versionadded:: 2.6
1398 The ``use_last_error`` and ``use_errno`` optional parameters
1401 .. data:: RTLD_GLOBAL
1404 Flag to use as *mode* parameter. On platforms where this flag is not available,
1405 it is defined as the integer zero.
1408 .. data:: RTLD_LOCAL
1411 Flag to use as *mode* parameter. On platforms where this is not available, it
1412 is the same as *RTLD_GLOBAL*.
1415 .. data:: DEFAULT_MODE
1418 The default mode which is used to load shared libraries. On OSX 10.3, this is
1419 *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*.
1421 Instances of these classes have no public methods, however :meth:`__getattr__`
1422 and :meth:`__getitem__` have special behavior: functions exported by the shared
1423 library can be accessed as attributes of by index. Please note that both
1424 :meth:`__getattr__` and :meth:`__getitem__` cache their result, so calling them
1425 repeatedly returns the same object each time.
1427 The following public attributes are available, their name starts with an
1428 underscore to not clash with exported function names:
1431 .. attribute:: PyDLL._handle
1433 The system handle used to access the library.
1436 .. attribute:: PyDLL._name
1438 The name of the library passed in the constructor.
1440 Shared libraries can also be loaded by using one of the prefabricated objects,
1441 which are instances of the :class:`LibraryLoader` class, either by calling the
1442 :meth:`LoadLibrary` method, or by retrieving the library as attribute of the
1446 .. class:: LibraryLoader(dlltype)
1448 Class which loads shared libraries. ``dlltype`` should be one of the
1449 :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types.
1451 :meth:`__getattr__` has special behavior: It allows to load a shared library by
1452 accessing it as attribute of a library loader instance. The result is cached,
1453 so repeated attribute accesses return the same library each time.
1456 .. method:: LoadLibrary(name)
1458 Load a shared library into the process and return it. This method always
1459 returns a new instance of the library.
1461 These prefabricated library loaders are available:
1467 Creates :class:`CDLL` instances.
1473 Windows only: Creates :class:`WinDLL` instances.
1479 Windows only: Creates :class:`OleDLL` instances.
1485 Creates :class:`PyDLL` instances.
1487 For accessing the C Python api directly, a ready-to-use Python shared library
1488 object is available:
1494 An instance of :class:`PyDLL` that exposes Python C api functions as attributes.
1495 Note that all these functions are assumed to return C ``int``, which is of
1496 course not always the truth, so you have to assign the correct :attr:`restype`
1497 attribute to use these functions.
1500 .. _ctypes-foreign-functions:
1505 As explained in the previous section, foreign functions can be accessed as
1506 attributes of loaded shared libraries. The function objects created in this way
1507 by default accept any number of arguments, accept any ctypes data instances as
1508 arguments, and return the default result type specified by the library loader.
1509 They are instances of a private class:
1514 Base class for C callable foreign functions.
1516 Instances of foreign functions are also C compatible data types; they
1517 represent C function pointers.
1519 This behavior can be customized by assigning to special attributes of the
1520 foreign function object.
1523 .. attribute:: restype
1525 Assign a ctypes type to specify the result type of the foreign function.
1526 Use ``None`` for ``void`` a function not returning anything.
1528 It is possible to assign a callable Python object that is not a ctypes
1529 type, in this case the function is assumed to return a C ``int``, and the
1530 callable will be called with this integer, allowing to do further
1531 processing or error checking. Using this is deprecated, for more flexible
1532 post processing or error checking use a ctypes data type as
1533 :attr:`restype` and assign a callable to the :attr:`errcheck` attribute.
1536 .. attribute:: argtypes
1538 Assign a tuple of ctypes types to specify the argument types that the
1539 function accepts. Functions using the ``stdcall`` calling convention can
1540 only be called with the same number of arguments as the length of this
1541 tuple; functions using the C calling convention accept additional,
1542 unspecified arguments as well.
1544 When a foreign function is called, each actual argument is passed to the
1545 :meth:`from_param` class method of the items in the :attr:`argtypes`
1546 tuple, this method allows to adapt the actual argument to an object that
1547 the foreign function accepts. For example, a :class:`c_char_p` item in
1548 the :attr:`argtypes` tuple will convert a unicode string passed as
1549 argument into an byte string using ctypes conversion rules.
1551 New: It is now possible to put items in argtypes which are not ctypes
1552 types, but each item must have a :meth:`from_param` method which returns a
1553 value usable as argument (integer, string, ctypes instance). This allows
1554 to define adapters that can adapt custom objects as function parameters.
1557 .. attribute:: errcheck
1559 Assign a Python function or another callable to this attribute. The
1560 callable will be called with three or more arguments:
1562 .. function:: callable(result, func, arguments)
1565 ``result`` is what the foreign function returns, as specified
1566 by the :attr:`restype` attribute.
1568 ``func`` is the foreign function object itself, this allows
1569 to reuse the same callable object to check or post process
1570 the results of several functions.
1572 ``arguments`` is a tuple containing the parameters originally
1573 passed to the function call, this allows to specialize the
1574 behavior on the arguments used.
1576 The object that this function returns will be returned from the
1577 foreign function call, but it can also check the result value
1578 and raise an exception if the foreign function call failed.
1581 .. exception:: ArgumentError()
1583 This exception is raised when a foreign function call cannot convert one of the
1587 .. _ctypes-function-prototypes:
1592 Foreign functions can also be created by instantiating function prototypes.
1593 Function prototypes are similar to function prototypes in C; they describe a
1594 function (return type, argument types, calling convention) without defining an
1595 implementation. The factory functions must be called with the desired result
1596 type and the argument types of the function.
1599 .. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
1601 The returned function prototype creates functions that use the standard C
1602 calling convention. The function will release the GIL during the call. If
1603 *use_errno* is set to True, the ctypes private copy of the system
1604 :data:`errno` variable is exchanged with the real :data:`errno` value before
1605 and after the call; *use_last_error* does the same for the Windows error
1608 .. versionchanged:: 2.6
1609 The optional *use_errno* and *use_last_error* parameters were added.
1612 .. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
1614 Windows only: The returned function prototype creates functions that use the
1615 ``stdcall`` calling convention, except on Windows CE where
1616 :func:`WINFUNCTYPE` is the same as :func:`CFUNCTYPE`. The function will
1617 release the GIL during the call. *use_errno* and *use_last_error* have the
1618 same meaning as above.
1621 .. function:: PYFUNCTYPE(restype, *argtypes)
1623 The returned function prototype creates functions that use the Python calling
1624 convention. The function will *not* release the GIL during the call.
1626 Function prototypes created by these factory functions can be instantiated in
1627 different ways, depending on the type and number of the parameters in the call:
1630 .. function:: prototype(address)
1634 Returns a foreign function at the specified address which must be an integer.
1637 .. function:: prototype(callable)
1641 Create a C callable function (a callback function) from a Python ``callable``.
1644 .. function:: prototype(func_spec[, paramflags])
1648 Returns a foreign function exported by a shared library. ``func_spec`` must be a
1649 2-tuple ``(name_or_ordinal, library)``. The first item is the name of the
1650 exported function as string, or the ordinal of the exported function as small
1651 integer. The second item is the shared library instance.
1654 .. function:: prototype(vtbl_index, name[, paramflags[, iid]])
1658 Returns a foreign function that will call a COM method. ``vtbl_index`` is the
1659 index into the virtual function table, a small non-negative integer. *name* is
1660 name of the COM method. *iid* is an optional pointer to the interface identifier
1661 which is used in extended error reporting.
1663 COM methods use a special calling convention: They require a pointer to the COM
1664 interface as first argument, in addition to those parameters that are specified
1665 in the :attr:`argtypes` tuple.
1667 The optional *paramflags* parameter creates foreign function wrappers with much
1668 more functionality than the features described above.
1670 *paramflags* must be a tuple of the same length as :attr:`argtypes`.
1672 Each item in this tuple contains further information about a parameter, it must
1673 be a tuple containing one, two, or three items.
1675 The first item is an integer containing a combination of direction
1676 flags for the parameter:
1679 Specifies an input parameter to the function.
1682 Output parameter. The foreign function fills in a value.
1685 Input parameter which defaults to the integer zero.
1687 The optional second item is the parameter name as string. If this is specified,
1688 the foreign function can be called with named parameters.
1690 The optional third item is the default value for this parameter.
1692 This example demonstrates how to wrap the Windows ``MessageBoxA`` function so
1693 that it supports default parameters and named arguments. The C declaration from
1694 the windows header file is this::
1696 WINUSERAPI int WINAPI
1703 Here is the wrapping with ``ctypes``::
1705 >>> from ctypes import c_int, WINFUNCTYPE, windll
1706 >>> from ctypes.wintypes import HWND, LPCSTR, UINT
1707 >>> prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
1708 >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
1709 >>> MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)
1712 The MessageBox foreign function can now be called in these ways::
1715 >>> MessageBox(text="Spam, spam, spam")
1716 >>> MessageBox(flags=2, text="foo bar")
1719 A second example demonstrates output parameters. The win32 ``GetWindowRect``
1720 function retrieves the dimensions of a specified window by copying them into
1721 ``RECT`` structure that the caller has to supply. Here is the C declaration::
1723 WINUSERAPI BOOL WINAPI
1728 Here is the wrapping with ``ctypes``::
1730 >>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
1731 >>> from ctypes.wintypes import BOOL, HWND, RECT
1732 >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
1733 >>> paramflags = (1, "hwnd"), (2, "lprect")
1734 >>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
1737 Functions with output parameters will automatically return the output parameter
1738 value if there is a single one, or a tuple containing the output parameter
1739 values when there are more than one, so the GetWindowRect function now returns a
1740 RECT instance, when called.
1742 Output parameters can be combined with the :attr:`errcheck` protocol to do
1743 further output processing and error checking. The win32 ``GetWindowRect`` api
1744 function returns a ``BOOL`` to signal success or failure, so this function could
1745 do the error checking, and raises an exception when the api call failed::
1747 >>> def errcheck(result, func, args):
1749 ... raise WinError()
1752 >>> GetWindowRect.errcheck = errcheck
1755 If the :attr:`errcheck` function returns the argument tuple it receives
1756 unchanged, ``ctypes`` continues the normal processing it does on the output
1757 parameters. If you want to return a tuple of window coordinates instead of a
1758 ``RECT`` instance, you can retrieve the fields in the function and return them
1759 instead, the normal processing will no longer take place::
1761 >>> def errcheck(result, func, args):
1763 ... raise WinError()
1765 ... return rc.left, rc.top, rc.bottom, rc.right
1767 >>> GetWindowRect.errcheck = errcheck
1771 .. _ctypes-utility-functions:
1777 .. function:: addressof(obj)
1779 Returns the address of the memory buffer as integer. ``obj`` must be an
1780 instance of a ctypes type.
1783 .. function:: alignment(obj_or_type)
1785 Returns the alignment requirements of a ctypes type. ``obj_or_type`` must be a
1786 ctypes type or instance.
1789 .. function:: byref(obj[, offset])
1791 Returns a light-weight pointer to ``obj``, which must be an
1792 instance of a ctypes type. ``offset`` defaults to zero, and must be
1793 an integer that will be added to the internal pointer value.
1795 ``byref(obj, offset)`` corresponds to this C code::
1797 (((char *)&obj) + offset)
1799 The returned object can only be used as a foreign function call
1800 parameter. It behaves similar to ``pointer(obj)``, but the
1801 construction is a lot faster.
1803 .. versionadded:: 2.6
1804 The ``offset`` optional argument was added.
1806 .. function:: cast(obj, type)
1808 This function is similar to the cast operator in C. It returns a new instance of
1809 ``type`` which points to the same memory block as ``obj``. ``type`` must be a
1810 pointer type, and ``obj`` must be an object that can be interpreted as a
1814 .. function:: create_string_buffer(init_or_size[, size])
1816 This function creates a mutable character buffer. The returned object is a
1817 ctypes array of :class:`c_char`.
1819 ``init_or_size`` must be an integer which specifies the size of the array, or a
1820 string which will be used to initialize the array items.
1822 If a string is specified as first argument, the buffer is made one item larger
1823 than the length of the string so that the last element in the array is a NUL
1824 termination character. An integer can be passed as second argument which allows
1825 to specify the size of the array if the length of the string should not be used.
1827 If the first parameter is a unicode string, it is converted into an 8-bit string
1828 according to ctypes conversion rules.
1831 .. function:: create_unicode_buffer(init_or_size[, size])
1833 This function creates a mutable unicode character buffer. The returned object is
1834 a ctypes array of :class:`c_wchar`.
1836 ``init_or_size`` must be an integer which specifies the size of the array, or a
1837 unicode string which will be used to initialize the array items.
1839 If a unicode string is specified as first argument, the buffer is made one item
1840 larger than the length of the string so that the last element in the array is a
1841 NUL termination character. An integer can be passed as second argument which
1842 allows to specify the size of the array if the length of the string should not
1845 If the first parameter is a 8-bit string, it is converted into an unicode string
1846 according to ctypes conversion rules.
1849 .. function:: DllCanUnloadNow()
1851 Windows only: This function is a hook which allows to implement in-process COM
1852 servers with ctypes. It is called from the DllCanUnloadNow function that the
1853 _ctypes extension dll exports.
1856 .. function:: DllGetClassObject()
1858 Windows only: This function is a hook which allows to implement in-process COM
1859 servers with ctypes. It is called from the DllGetClassObject function that the
1860 ``_ctypes`` extension dll exports.
1862 .. function:: find_library(name)
1863 :module: ctypes.util
1865 Try to find a library and return a pathname. *name* is the library name
1866 without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version
1867 number (this is the form used for the posix linker option :option:`-l`). If
1868 no library can be found, returns ``None``.
1870 The exact functionality is system dependent.
1872 .. versionchanged:: 2.6
1873 Windows only: ``find_library("m")`` or
1874 ``find_library("c")`` return the result of a call to
1877 .. function:: find_msvcrt()
1878 :module: ctypes.util
1880 Windows only: return the filename of the VC runtype library used
1881 by Python, and by the extension modules. If the name of the
1882 library cannot be determined, ``None`` is returned.
1884 If you need to free memory, for example, allocated by an extension
1885 module with a call to the ``free(void *)``, it is important that you
1886 use the function in the same library that allocated the memory.
1888 .. versionadded:: 2.6
1890 .. function:: FormatError([code])
1892 Windows only: Returns a textual description of the error code. If no error code
1893 is specified, the last error code is used by calling the Windows api function
1897 .. function:: GetLastError()
1899 Windows only: Returns the last error code set by Windows in the calling thread.
1900 This function calls the Windows `GetLastError()` function directly,
1901 it does not return the ctypes-private copy of the error code.
1903 .. function:: get_errno()
1905 Returns the current value of the ctypes-private copy of the system
1906 :data:`errno` variable in the calling thread.
1908 .. versionadded:: 2.6
1910 .. function:: get_last_error()
1912 Windows only: returns the current value of the ctypes-private copy of the system
1913 :data:`LastError` variable in the calling thread.
1915 .. versionadded:: 2.6
1917 .. function:: memmove(dst, src, count)
1919 Same as the standard C memmove library function: copies *count* bytes from
1920 ``src`` to *dst*. *dst* and ``src`` must be integers or ctypes instances that
1921 can be converted to pointers.
1924 .. function:: memset(dst, c, count)
1926 Same as the standard C memset library function: fills the memory block at
1927 address *dst* with *count* bytes of value *c*. *dst* must be an integer
1928 specifying an address, or a ctypes instance.
1931 .. function:: POINTER(type)
1933 This factory function creates and returns a new ctypes pointer type. Pointer
1934 types are cached an reused internally, so calling this function repeatedly is
1935 cheap. type must be a ctypes type.
1938 .. function:: pointer(obj)
1940 This function creates a new pointer instance, pointing to ``obj``. The returned
1941 object is of the type POINTER(type(obj)).
1943 Note: If you just want to pass a pointer to an object to a foreign function
1944 call, you should use ``byref(obj)`` which is much faster.
1947 .. function:: resize(obj, size)
1949 This function resizes the internal memory buffer of obj, which must be an
1950 instance of a ctypes type. It is not possible to make the buffer smaller than
1951 the native size of the objects type, as given by sizeof(type(obj)), but it is
1952 possible to enlarge the buffer.
1955 .. function:: set_conversion_mode(encoding, errors)
1957 This function sets the rules that ctypes objects use when converting between
1958 8-bit strings and unicode strings. encoding must be a string specifying an
1959 encoding, like ``'utf-8'`` or ``'mbcs'``, errors must be a string specifying the
1960 error handling on encoding/decoding errors. Examples of possible values are
1961 ``"strict"``, ``"replace"``, or ``"ignore"``.
1963 ``set_conversion_mode`` returns a 2-tuple containing the previous conversion
1964 rules. On windows, the initial conversion rules are ``('mbcs', 'ignore')``, on
1965 other systems ``('ascii', 'strict')``.
1968 .. function:: set_errno(value)
1970 Set the current value of the ctypes-private copy of the system :data:`errno`
1971 variable in the calling thread to *value* and return the previous value.
1973 .. versionadded:: 2.6
1975 .. function:: set_last_error(value)
1977 Windows only: set the current value of the ctypes-private copy of the system
1978 :data:`LastError` variable in the calling thread to *value* and return the
1981 .. versionadded:: 2.6
1983 .. function:: sizeof(obj_or_type)
1985 Returns the size in bytes of a ctypes type or instance memory buffer. Does the
1986 same as the C ``sizeof()`` function.
1989 .. function:: string_at(address[, size])
1991 This function returns the string starting at memory address address. If size
1992 is specified, it is used as size, otherwise the string is assumed to be
1996 .. function:: WinError(code=None, descr=None)
1998 Windows only: this function is probably the worst-named thing in ctypes. It
1999 creates an instance of WindowsError. If *code* is not specified,
2000 ``GetLastError`` is called to determine the error code. If ``descr`` is not
2001 specified, :func:`FormatError` is called to get a textual description of the
2005 .. function:: wstring_at(address)
2007 This function returns the wide character string starting at memory address
2008 ``address`` as unicode string. If ``size`` is specified, it is used as the
2009 number of characters of the string, otherwise the string is assumed to be
2013 .. _ctypes-data-types:
2021 This non-public class is the common base class of all ctypes data types. Among
2022 other things, all ctypes type instances contain a memory block that hold C
2023 compatible data; the address of the memory block is returned by the
2024 ``addressof()`` helper function. Another instance variable is exposed as
2025 :attr:`_objects`; this contains other Python objects that need to be kept alive
2026 in case the memory block contains pointers.
2028 Common methods of ctypes data types, these are all class methods (to be
2029 exact, they are methods of the :term:`metaclass`):
2032 .. method:: _CData.from_buffer(source[, offset])
2034 This method returns a ctypes instance that shares the buffer of
2035 the ``source`` object. The ``source`` object must support the
2036 writeable buffer interface. The optional ``offset`` parameter
2037 specifies an offset into the source buffer in bytes; the default
2038 is zero. If the source buffer is not large enough a ValueError
2041 .. versionadded:: 2.6
2043 .. method:: _CData.from_buffer_copy(source[, offset])
2045 This method creates a ctypes instance, copying the buffer from
2046 the source object buffer which must be readable. The optional
2047 ``offset`` parameter specifies an offset into the source buffer
2048 in bytes; the default is zero. If the source buffer is not
2049 large enough a ValueError is raised.
2051 .. versionadded:: 2.6
2054 .. method:: from_address(address)
2056 This method returns a ctypes type instance using the memory specified by
2057 address which must be an integer.
2060 .. method:: from_param(obj)
2062 This method adapts *obj* to a ctypes type. It is called with the actual
2063 object used in a foreign function call when the type is present in the
2064 foreign function's :attr:`argtypes` tuple; it must return an object that
2065 can be used as a function call parameter.
2067 All ctypes data types have a default implementation of this classmethod
2068 that normally returns ``obj`` if that is an instance of the type. Some
2069 types accept other objects as well.
2072 .. method:: in_dll(library, name)
2074 This method returns a ctypes type instance exported by a shared
2075 library. *name* is the name of the symbol that exports the data, *library*
2076 is the loaded shared library.
2079 Common instance variables of ctypes data types:
2082 .. attribute:: _b_base_
2084 Sometimes ctypes data instances do not own the memory block they contain,
2085 instead they share part of the memory block of a base object. The
2086 :attr:`_b_base_` read-only member is the root ctypes object that owns the
2090 .. attribute:: _b_needsfree_
2092 This read-only variable is true when the ctypes data instance has
2093 allocated the memory block itself, false otherwise.
2096 .. attribute:: _objects
2098 This member is either ``None`` or a dictionary containing Python objects
2099 that need to be kept alive so that the memory block contents is kept
2100 valid. This object is only exposed for debugging; never modify the
2101 contents of this dictionary.
2104 .. _ctypes-fundamental-data-types-2:
2106 Fundamental data types
2107 ^^^^^^^^^^^^^^^^^^^^^^
2110 .. class:: _SimpleCData
2112 This non-public class is the base class of all fundamental ctypes data types. It
2113 is mentioned here because it contains the common attributes of the fundamental
2114 ctypes data types. ``_SimpleCData`` is a subclass of ``_CData``, so it inherits
2115 their methods and attributes.
2117 .. versionchanged:: 2.6
2118 ctypes data types that are not and do not contain pointers can
2121 Instances have a single attribute:
2124 .. attribute:: value
2126 This attribute contains the actual value of the instance. For integer and
2127 pointer types, it is an integer, for character types, it is a single
2128 character string, for character pointer types it is a Python string or
2131 When the ``value`` attribute is retrieved from a ctypes instance, usually
2132 a new object is returned each time. ``ctypes`` does *not* implement
2133 original object return, always a new object is constructed. The same is
2134 true for all other ctypes object instances.
2136 Fundamental data types, when returned as foreign function call results, or, for
2137 example, by retrieving structure field members or array items, are transparently
2138 converted to native Python types. In other words, if a foreign function has a
2139 :attr:`restype` of :class:`c_char_p`, you will always receive a Python string,
2140 *not* a :class:`c_char_p` instance.
2142 Subclasses of fundamental data types do *not* inherit this behavior. So, if a
2143 foreign functions :attr:`restype` is a subclass of :class:`c_void_p`, you will
2144 receive an instance of this subclass from the function call. Of course, you can
2145 get the value of the pointer by accessing the ``value`` attribute.
2147 These are the fundamental ctypes data types:
2152 Represents the C signed char datatype, and interprets the value as small
2153 integer. The constructor accepts an optional integer initializer; no overflow
2159 Represents the C char datatype, and interprets the value as a single character.
2160 The constructor accepts an optional string initializer, the length of the string
2161 must be exactly one character.
2166 Represents the C char \* datatype, which must be a pointer to a zero-terminated
2167 string. The constructor accepts an integer address, or a string.
2172 Represents the C double datatype. The constructor accepts an optional float
2176 .. class:: c_longdouble
2178 Represents the C long double datatype. The constructor accepts an
2179 optional float initializer. On platforms where ``sizeof(long
2180 double) == sizeof(double)`` it is an alias to :class:`c_double`.
2182 .. versionadded:: 2.6
2186 Represents the C float datatype. The constructor accepts an optional float
2192 Represents the C signed int datatype. The constructor accepts an optional
2193 integer initializer; no overflow checking is done. On platforms where
2194 ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`.
2199 Represents the C 8-bit ``signed int`` datatype. Usually an alias for
2205 Represents the C 16-bit signed int datatype. Usually an alias for
2211 Represents the C 32-bit signed int datatype. Usually an alias for
2217 Represents the C 64-bit ``signed int`` datatype. Usually an alias for
2218 :class:`c_longlong`.
2223 Represents the C ``signed long`` datatype. The constructor accepts an optional
2224 integer initializer; no overflow checking is done.
2227 .. class:: c_longlong
2229 Represents the C ``signed long long`` datatype. The constructor accepts an
2230 optional integer initializer; no overflow checking is done.
2235 Represents the C ``signed short`` datatype. The constructor accepts an optional
2236 integer initializer; no overflow checking is done.
2241 Represents the C ``size_t`` datatype.
2246 Represents the C ``unsigned char`` datatype, it interprets the value as small
2247 integer. The constructor accepts an optional integer initializer; no overflow
2253 Represents the C ``unsigned int`` datatype. The constructor accepts an optional
2254 integer initializer; no overflow checking is done. On platforms where
2255 ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`.
2260 Represents the C 8-bit unsigned int datatype. Usually an alias for
2266 Represents the C 16-bit unsigned int datatype. Usually an alias for
2272 Represents the C 32-bit unsigned int datatype. Usually an alias for
2278 Represents the C 64-bit unsigned int datatype. Usually an alias for
2279 :class:`c_ulonglong`.
2284 Represents the C ``unsigned long`` datatype. The constructor accepts an optional
2285 integer initializer; no overflow checking is done.
2288 .. class:: c_ulonglong
2290 Represents the C ``unsigned long long`` datatype. The constructor accepts an
2291 optional integer initializer; no overflow checking is done.
2296 Represents the C ``unsigned short`` datatype. The constructor accepts an
2297 optional integer initializer; no overflow checking is done.
2302 Represents the C ``void *`` type. The value is represented as integer. The
2303 constructor accepts an optional integer initializer.
2308 Represents the C ``wchar_t`` datatype, and interprets the value as a single
2309 character unicode string. The constructor accepts an optional string
2310 initializer, the length of the string must be exactly one character.
2313 .. class:: c_wchar_p
2315 Represents the C ``wchar_t *`` datatype, which must be a pointer to a
2316 zero-terminated wide character string. The constructor accepts an integer
2317 address, or a string.
2322 Represent the C ``bool`` datatype (more accurately, _Bool from C99). Its value
2323 can be True or False, and the constructor accepts any object that has a truth
2326 .. versionadded:: 2.6
2331 Windows only: Represents a :class:`HRESULT` value, which contains success or
2332 error information for a function or method call.
2335 .. class:: py_object
2337 Represents the C ``PyObject *`` datatype. Calling this without an argument
2338 creates a ``NULL`` ``PyObject *`` pointer.
2340 The ``ctypes.wintypes`` module provides quite some other Windows specific data
2341 types, for example ``HWND``, ``WPARAM``, or ``DWORD``. Some useful structures
2342 like ``MSG`` or ``RECT`` are also defined.
2345 .. _ctypes-structured-data-types:
2347 Structured data types
2348 ^^^^^^^^^^^^^^^^^^^^^
2351 .. class:: Union(*args, **kw)
2353 Abstract base class for unions in native byte order.
2356 .. class:: BigEndianStructure(*args, **kw)
2358 Abstract base class for structures in *big endian* byte order.
2361 .. class:: LittleEndianStructure(*args, **kw)
2363 Abstract base class for structures in *little endian* byte order.
2365 Structures with non-native byte order cannot contain pointer type fields, or any
2366 other data types containing pointer type fields.
2369 .. class:: Structure(*args, **kw)
2371 Abstract base class for structures in *native* byte order.
2373 Concrete structure and union types must be created by subclassing one of these
2374 types, and at least define a :attr:`_fields_` class variable. ``ctypes`` will
2375 create :term:`descriptor`\s which allow reading and writing the fields by direct
2376 attribute accesses. These are the
2379 .. attribute:: _fields_
2381 A sequence defining the structure fields. The items must be 2-tuples or
2382 3-tuples. The first item is the name of the field, the second item
2383 specifies the type of the field; it can be any ctypes data type.
2385 For integer type fields like :class:`c_int`, a third optional item can be
2386 given. It must be a small positive integer defining the bit width of the
2389 Field names must be unique within one structure or union. This is not
2390 checked, only one field can be accessed when names are repeated.
2392 It is possible to define the :attr:`_fields_` class variable *after* the
2393 class statement that defines the Structure subclass, this allows to create
2394 data types that directly or indirectly reference themselves::
2396 class List(Structure):
2398 List._fields_ = [("pnext", POINTER(List)),
2402 The :attr:`_fields_` class variable must, however, be defined before the
2403 type is first used (an instance is created, ``sizeof()`` is called on it,
2404 and so on). Later assignments to the :attr:`_fields_` class variable will
2405 raise an AttributeError.
2407 Structure and union subclass constructors accept both positional and named
2408 arguments. Positional arguments are used to initialize the fields in the
2409 same order as they appear in the :attr:`_fields_` definition, named
2410 arguments are used to initialize the fields with the corresponding name.
2412 It is possible to defined sub-subclasses of structure types, they inherit
2413 the fields of the base class plus the :attr:`_fields_` defined in the
2414 sub-subclass, if any.
2417 .. attribute:: _pack_
2419 An optional small integer that allows to override the alignment of
2420 structure fields in the instance. :attr:`_pack_` must already be defined
2421 when :attr:`_fields_` is assigned, otherwise it will have no effect.
2424 .. attribute:: _anonymous_
2426 An optional sequence that lists the names of unnamed (anonymous) fields.
2427 ``_anonymous_`` must be already defined when :attr:`_fields_` is assigned,
2428 otherwise it will have no effect.
2430 The fields listed in this variable must be structure or union type fields.
2431 ``ctypes`` will create descriptors in the structure type that allows to
2432 access the nested fields directly, without the need to create the
2433 structure or union field.
2435 Here is an example type (Windows)::
2438 _fields_ = [("lptdesc", POINTER(TYPEDESC)),
2439 ("lpadesc", POINTER(ARRAYDESC)),
2440 ("hreftype", HREFTYPE)]
2442 class TYPEDESC(Structure):
2443 _anonymous_ = ("u",)
2444 _fields_ = [("u", _U),
2448 The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field
2449 specifies which one of the union fields is valid. Since the ``u`` field
2450 is defined as anonymous field, it is now possible to access the members
2451 directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc``
2452 are equivalent, but the former is faster since it does not need to create
2453 a temporary union instance::
2457 td.lptdesc = POINTER(some_type)
2458 td.u.lptdesc = POINTER(some_type)
2460 It is possible to defined sub-subclasses of structures, they inherit the fields
2461 of the base class. If the subclass definition has a separate :attr:`_fields_`
2462 variable, the fields specified in this are appended to the fields of the base
2465 Structure and union constructors accept both positional and keyword arguments.
2466 Positional arguments are used to initialize member fields in the same order as
2467 they are appear in :attr:`_fields_`. Keyword arguments in the constructor are
2468 interpreted as attribute assignments, so they will initialize :attr:`_fields_`
2469 with the same name, or create new attributes for names not present in
2473 .. _ctypes-arrays-pointers:
2478 Not yet written - please see the sections :ref:`ctypes-pointers` and
2479 section :ref:`ctypes-arrays` in the tutorial.