2
:mod:`ctypes` --- A foreign function library for Python.
3
========================================================
6
:synopsis: A foreign function library for Python.
7
.. moduleauthor:: Thomas Heller <theller@python.net>
12
``ctypes`` is a foreign function library for Python. It provides C compatible
13
data types, and allows calling functions in DLLs or shared libraries. It can be
14
used to wrap these libraries in pure Python.
17
.. _ctypes-ctypes-tutorial:
22
Note: The code samples in this tutorial use ``doctest`` to make sure that they
23
actually work. Since some code samples behave differently under Linux, Windows,
24
or Mac OS X, they contain doctest directives in comments.
26
Note: Some code samples reference the ctypes :class:`c_int` type. This type is
27
an alias for the :class:`c_long` type on 32-bit systems. So, you should not be
28
confused if :class:`c_long` is printed if you would expect :class:`c_int` ---
29
they are actually the same type.
32
.. _ctypes-loading-dynamic-link-libraries:
34
Loading dynamic link libraries
35
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
37
``ctypes`` exports the *cdll*, and on Windows *windll* and *oledll*
38
objects, for loading dynamic link libraries.
40
You load libraries by accessing them as attributes of these objects. *cdll*
41
loads libraries which export functions using the standard ``cdecl`` calling
42
convention, while *windll* libraries call functions using the ``stdcall``
43
calling convention. *oledll* also uses the ``stdcall`` calling convention, and
44
assumes the functions return a Windows :class:`HRESULT` error code. The error
45
code is used to automatically raise a :class:`WindowsError` exception when
46
the function call fails.
48
Here are some examples for Windows. Note that ``msvcrt`` is the MS standard C
49
library containing most standard C functions, and uses the cdecl calling
52
>>> from ctypes import *
53
>>> print windll.kernel32 # doctest: +WINDOWS
54
<WinDLL 'kernel32', handle ... at ...>
55
>>> print cdll.msvcrt # doctest: +WINDOWS
56
<CDLL 'msvcrt', handle ... at ...>
57
>>> libc = cdll.msvcrt # doctest: +WINDOWS
60
Windows appends the usual ``.dll`` file suffix automatically.
62
On Linux, it is required to specify the filename *including* the extension to
63
load a library, so attribute access can not be used to load libraries. Either the
64
:meth:`LoadLibrary` method of the dll loaders should be used, or you should load
65
the library by creating an instance of CDLL by calling the constructor::
67
>>> cdll.LoadLibrary("libc.so.6") # doctest: +LINUX
68
<CDLL 'libc.so.6', handle ... at ...>
69
>>> libc = CDLL("libc.so.6") # doctest: +LINUX
70
>>> libc # doctest: +LINUX
71
<CDLL 'libc.so.6', handle ... at ...>
74
.. XXX Add section for Mac OS X.
77
.. _ctypes-accessing-functions-from-loaded-dlls:
79
Accessing functions from loaded dlls
80
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
82
Functions are accessed as attributes of dll objects::
84
>>> from ctypes import *
86
<_FuncPtr object at 0x...>
87
>>> print windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
88
<_FuncPtr object at 0x...>
89
>>> print windll.kernel32.MyOwnFunction # doctest: +WINDOWS
90
Traceback (most recent call last):
91
File "<stdin>", line 1, in ?
92
File "ctypes.py", line 239, in __getattr__
93
func = _StdcallFuncPtr(name, self)
94
AttributeError: function 'MyOwnFunction' not found
97
Note that win32 system dlls like ``kernel32`` and ``user32`` often export ANSI
98
as well as UNICODE versions of a function. The UNICODE version is exported with
99
an ``W`` appended to the name, while the ANSI version is exported with an ``A``
100
appended to the name. The win32 ``GetModuleHandle`` function, which returns a
101
*module handle* for a given module name, has the following C prototype, and a
102
macro is used to expose one of them as ``GetModuleHandle`` depending on whether
103
UNICODE is defined or not::
106
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
107
/* UNICODE version */
108
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
110
*windll* does not try to select one of them by magic, you must access the
111
version you need by specifying ``GetModuleHandleA`` or ``GetModuleHandleW``
112
explicitly, and then call it with strings or unicode strings
115
Sometimes, dlls export functions with names which aren't valid Python
116
identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use ``getattr``
117
to retrieve the function::
119
>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") # doctest: +WINDOWS
120
<_FuncPtr object at 0x...>
123
On Windows, some dlls export functions not by name but by ordinal. These
124
functions can be accessed by indexing the dll object with the ordinal number::
126
>>> cdll.kernel32[1] # doctest: +WINDOWS
127
<_FuncPtr object at 0x...>
128
>>> cdll.kernel32[0] # doctest: +WINDOWS
129
Traceback (most recent call last):
130
File "<stdin>", line 1, in ?
131
File "ctypes.py", line 310, in __getitem__
132
func = _StdcallFuncPtr(name, self)
133
AttributeError: function ordinal 0 not found
137
.. _ctypes-calling-functions:
142
You can call these functions like any other Python callable. This example uses
143
the ``time()`` function, which returns system time in seconds since the Unix
144
epoch, and the ``GetModuleHandleA()`` function, which returns a win32 module
147
This example calls both functions with a NULL pointer (``None`` should be used
148
as the NULL pointer)::
150
>>> print libc.time(None) # doctest: +SKIP
152
>>> print hex(windll.kernel32.GetModuleHandleA(None)) # doctest: +WINDOWS
156
``ctypes`` tries to protect you from calling functions with the wrong number of
157
arguments or the wrong calling convention. Unfortunately this only works on
158
Windows. It does this by examining the stack after the function returns, so
159
although an error is raised the function *has* been called::
161
>>> windll.kernel32.GetModuleHandleA() # doctest: +WINDOWS
162
Traceback (most recent call last):
163
File "<stdin>", line 1, in ?
164
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
165
>>> windll.kernel32.GetModuleHandleA(0, 0) # doctest: +WINDOWS
166
Traceback (most recent call last):
167
File "<stdin>", line 1, in ?
168
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
171
The same exception is raised when you call an ``stdcall`` function with the
172
``cdecl`` calling convention, or vice versa::
174
>>> cdll.kernel32.GetModuleHandleA(None) # doctest: +WINDOWS
175
Traceback (most recent call last):
176
File "<stdin>", line 1, in ?
177
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
180
>>> windll.msvcrt.printf("spam") # doctest: +WINDOWS
181
Traceback (most recent call last):
182
File "<stdin>", line 1, in ?
183
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
186
To find out the correct calling convention you have to look into the C header
187
file or the documentation for the function you want to call.
189
On Windows, ``ctypes`` uses win32 structured exception handling to prevent
190
crashes from general protection faults when functions are called with invalid
193
>>> windll.kernel32.GetModuleHandleA(32) # doctest: +WINDOWS
194
Traceback (most recent call last):
195
File "<stdin>", line 1, in ?
196
WindowsError: exception: access violation reading 0x00000020
199
There are, however, enough ways to crash Python with ``ctypes``, so you should
202
``None``, integers, longs, byte strings and unicode strings are the only native
203
Python objects that can directly be used as parameters in these function calls.
204
``None`` is passed as a C ``NULL`` pointer, byte strings and unicode strings are
205
passed as pointer to the memory block that contains their data (``char *`` or
206
``wchar_t *``). Python integers and Python longs are passed as the platforms
207
default C ``int`` type, their value is masked to fit into the C type.
209
Before we move on calling functions with other parameter types, we have to learn
210
more about ``ctypes`` data types.
213
.. _ctypes-fundamental-data-types:
215
Fundamental data types
216
^^^^^^^^^^^^^^^^^^^^^^
218
``ctypes`` defines a number of primitive C compatible data types :
220
+----------------------+--------------------------------+----------------------------+
221
| ctypes type | C type | Python type |
222
+======================+================================+============================+
223
| :class:`c_char` | ``char`` | 1-character string |
224
+----------------------+--------------------------------+----------------------------+
225
| :class:`c_wchar` | ``wchar_t`` | 1-character unicode string |
226
+----------------------+--------------------------------+----------------------------+
227
| :class:`c_byte` | ``char`` | int/long |
228
+----------------------+--------------------------------+----------------------------+
229
| :class:`c_ubyte` | ``unsigned char`` | int/long |
230
+----------------------+--------------------------------+----------------------------+
231
| :class:`c_short` | ``short`` | int/long |
232
+----------------------+--------------------------------+----------------------------+
233
| :class:`c_ushort` | ``unsigned short`` | int/long |
234
+----------------------+--------------------------------+----------------------------+
235
| :class:`c_int` | ``int`` | int/long |
236
+----------------------+--------------------------------+----------------------------+
237
| :class:`c_uint` | ``unsigned int`` | int/long |
238
+----------------------+--------------------------------+----------------------------+
239
| :class:`c_long` | ``long`` | int/long |
240
+----------------------+--------------------------------+----------------------------+
241
| :class:`c_ulong` | ``unsigned long`` | int/long |
242
+----------------------+--------------------------------+----------------------------+
243
| :class:`c_longlong` | ``__int64`` or ``long long`` | int/long |
244
+----------------------+--------------------------------+----------------------------+
245
| :class:`c_ulonglong` | ``unsigned __int64`` or | int/long |
246
| | ``unsigned long long`` | |
247
+----------------------+--------------------------------+----------------------------+
248
| :class:`c_float` | ``float`` | float |
249
+----------------------+--------------------------------+----------------------------+
250
| :class:`c_double` | ``double`` | float |
251
+----------------------+--------------------------------+----------------------------+
252
| :class:`c_longdouble`| ``long double`` | float |
253
+----------------------+--------------------------------+----------------------------+
254
| :class:`c_char_p` | ``char *`` (NUL terminated) | string or ``None`` |
255
+----------------------+--------------------------------+----------------------------+
256
| :class:`c_wchar_p` | ``wchar_t *`` (NUL terminated) | unicode or ``None`` |
257
+----------------------+--------------------------------+----------------------------+
258
| :class:`c_void_p` | ``void *`` | int/long or ``None`` |
259
+----------------------+--------------------------------+----------------------------+
262
All these types can be created by calling them with an optional initializer of
263
the correct type and value::
267
>>> c_char_p("Hello, World")
268
c_char_p('Hello, World')
273
Since these types are mutable, their value can also be changed afterwards::
285
Assigning a new value to instances of the pointer types :class:`c_char_p`,
286
:class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they
287
point to, *not the contents* of the memory block (of course not, because Python
288
strings are immutable)::
290
>>> s = "Hello, World"
291
>>> c_s = c_char_p(s)
293
c_char_p('Hello, World')
294
>>> c_s.value = "Hi, there"
296
c_char_p('Hi, there')
297
>>> print s # first string is unchanged
301
You should be careful, however, not to pass them to functions expecting pointers
302
to mutable memory. If you need mutable memory blocks, ctypes has a
303
``create_string_buffer`` function which creates these in various ways. The
304
current memory block contents can be accessed (or changed) with the ``raw``
305
property; if you want to access it as NUL terminated string, use the ``value``
308
>>> from ctypes import *
309
>>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes
310
>>> print sizeof(p), repr(p.raw)
312
>>> p = create_string_buffer("Hello") # create a buffer containing a NUL terminated string
313
>>> print sizeof(p), repr(p.raw)
315
>>> print repr(p.value)
317
>>> p = create_string_buffer("Hello", 10) # create a 10 byte buffer
318
>>> print sizeof(p), repr(p.raw)
319
10 'Hello\x00\x00\x00\x00\x00'
321
>>> print sizeof(p), repr(p.raw)
322
10 'Hi\x00lo\x00\x00\x00\x00\x00'
325
The ``create_string_buffer`` function replaces the ``c_buffer`` function (which
326
is still available as an alias), as well as the ``c_string`` function from
327
earlier ctypes releases. To create a mutable memory block containing unicode
328
characters of the C type ``wchar_t`` use the ``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
``sys.stdout``, so these examples will only work at the console prompt, not from
338
within *IDLE* or *PythonWin*::
340
>>> printf = libc.printf
341
>>> printf("Hello, %s\n", "World!")
344
>>> printf("Hello, %S", 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 ``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
Integer 1234, double 3.1400001049
366
.. _ctypes-calling-functions-with-own-custom-data-types:
368
Calling functions with your own custom data types
369
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
371
You can also customize ``ctypes`` argument conversion to allow instances of your
372
own classes be used as function arguments. ``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 ``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", "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 ``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 ``int`` type. Other return
439
types can be specified by setting the :attr:`restype` attribute of the function
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
``ctypes`` exports the :func:`byref` function which is used to pass parameters
515
by reference. The same effect can be achieved with the ``pointer`` function,
516
although ``pointer`` does a lot more work since it constructs a real pointer
517
object, so it is faster to use :func:`byref` if you don't need the pointer
518
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 ``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 ``ctypes`` type like :class:`c_int`, or any other
544
derived ``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
550
>>> from ctypes import *
551
>>> class POINT(Structure):
552
... _fields_ = [("x", c_int),
555
>>> point = POINT(10, 20)
556
>>> print point.x, point.y
558
>>> point = POINT(y=5)
559
>>> print point.x, point.y
562
Traceback (most recent call last):
563
File "<stdin>", line 1, in ?
564
ValueError: too many initializers
567
You can, however, build much more complicated structures. Structures can itself
568
contain other structures by using a structure as a field type.
570
Here is a RECT structure which contains two POINTs named ``upperleft`` and
573
>>> class RECT(Structure):
574
... _fields_ = [("upperleft", POINT),
575
... ("lowerright", POINT)]
578
>>> print rc.upperleft.x, rc.upperleft.y
580
>>> print rc.lowerright.x, rc.lowerright.y
584
Nested structures can also be initialized in the constructor in several ways::
586
>>> r = RECT(POINT(1, 2), POINT(3, 4))
587
>>> r = RECT((1, 2), (3, 4))
589
Field :term:`descriptor`\s can be retrieved from the *class*, they are useful
590
for debugging because they can provide useful information::
593
<Field type=c_long, ofs=0, size=4>
595
<Field type=c_long, ofs=4, size=4>
599
.. _ctypes-structureunion-alignment-byte-order:
601
Structure/union alignment and byte order
602
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
604
By default, Structure and Union fields are aligned in the same way the C
605
compiler does it. It is possible to override this behavior be specifying a
606
:attr:`_pack_` class attribute in the subclass definition. This must be set to a
607
positive integer and specifies the maximum alignment for the fields. This is
608
what ``#pragma pack(n)`` also does in MSVC.
610
``ctypes`` uses the native byte order for Structures and Unions. To build
611
structures with non-native byte order, you can use one of the
612
BigEndianStructure, LittleEndianStructure, BigEndianUnion, and LittleEndianUnion
613
base classes. These 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 ``pointer`` function on a
694
>>> from ctypes import *
699
Pointer instances have a ``contents`` attribute which returns the object to
700
which the pointer points, the ``i`` object above::
706
Note that ``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 .contents attribute.
726
Pointer instances can also be indexed with integers::
732
Assigning to an integer index changes the pointed to value::
741
It is also possible to use indexes different from 0, but you must know what
742
you're doing, just as in C: You can access or change arbitrary memory locations.
743
Generally you only use this feature if you receive a pointer from a C function,
744
and you *know* that the pointer actually points to an array instead of a single
747
Behind the scenes, the ``pointer`` function does more than simply create pointer
748
instances, it has to create pointer *types* first. This is done with the
749
``POINTER`` function, which accepts any ``ctypes`` type, and returns a new
752
>>> PI = POINTER(c_int)
754
<class 'ctypes.LP_c_long'>
756
Traceback (most recent call last):
757
File "<stdin>", line 1, in ?
758
TypeError: expected c_long instead of int
760
<ctypes.LP_c_long object at 0x...>
763
Calling the pointer type without an argument creates a ``NULL`` pointer.
764
``NULL`` pointers have a ``False`` boolean value::
766
>>> null_ptr = POINTER(c_int)()
767
>>> print bool(null_ptr)
771
``ctypes`` checks for ``NULL`` when dereferencing pointers (but dereferencing
772
invalid non-\ ``NULL`` pointers would crash Python)::
775
Traceback (most recent call last):
777
ValueError: NULL pointer access
780
>>> null_ptr[0] = 1234
781
Traceback (most recent call last):
783
ValueError: NULL pointer access
787
.. _ctypes-type-conversions:
792
Usually, ctypes does strict type checking. This means, if you have
793
``POINTER(c_int)`` in the :attr:`argtypes` list of a function or as the type of
794
a member field in a structure definition, only instances of exactly the same
795
type are accepted. There are some exceptions to this rule, where ctypes accepts
796
other objects. For example, you can pass compatible array instances instead of
797
pointer types. So, for ``POINTER(c_int)``, ctypes accepts an array of c_int::
799
>>> class Bar(Structure):
800
... _fields_ = [("count", c_int), ("values", POINTER(c_int))]
803
>>> bar.values = (c_int * 3)(1, 2, 3)
805
>>> for i in range(bar.count):
806
... print bar.values[i]
813
To set a POINTER type field to ``NULL``, you can assign ``None``::
815
>>> bar.values = None
818
.. XXX list other conversions...
820
Sometimes you have instances of incompatible types. In C, you can cast one
821
type into another type. ``ctypes`` provides a ``cast`` function which can be
822
used in the same way. The ``Bar`` structure defined above accepts
823
``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field,
824
but not instances of other types::
826
>>> bar.values = (c_byte * 4)()
827
Traceback (most recent call last):
828
File "<stdin>", line 1, in ?
829
TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
832
For these cases, the ``cast`` function is handy.
834
The ``cast`` function can be used to cast a ctypes instance into a pointer to a
835
different ctypes data type. ``cast`` takes two parameters, a ctypes object that
836
is or can be converted to a pointer of some kind, and a ctypes pointer type. It
837
returns an instance of the second argument, which references the same memory
838
block as the first argument::
840
>>> a = (c_byte * 4)()
841
>>> cast(a, POINTER(c_int))
842
<ctypes.LP_c_long object at ...>
845
So, ``cast`` can be used to assign to the ``values`` field of ``Bar`` the
849
>>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
850
>>> print bar.values[0]
855
.. _ctypes-incomplete-types:
860
*Incomplete Types* are structures, unions or arrays whose members are not yet
861
specified. In C, they are specified by forward declarations, which are defined
864
struct cell; /* forward declaration */
871
The straightforward translation into ctypes code would be this, but it does not
874
>>> class cell(Structure):
875
... _fields_ = [("name", c_char_p),
876
... ("next", POINTER(cell))]
878
Traceback (most recent call last):
879
File "<stdin>", line 1, in ?
880
File "<stdin>", line 2, in cell
881
NameError: name 'cell' is not defined
884
because the new ``class cell`` is not available in the class statement itself.
885
In ``ctypes``, we can define the ``cell`` class and set the :attr:`_fields_`
886
attribute later, after the class statement::
888
>>> from ctypes import *
889
>>> class cell(Structure):
892
>>> cell._fields_ = [("name", c_char_p),
893
... ("next", POINTER(cell))]
896
Lets try it. We create two instances of ``cell``, and let them point to each
897
other, and finally follow the pointer chain a few times::
903
>>> c1.next = pointer(c2)
904
>>> c2.next = pointer(c1)
906
>>> for i in range(8):
910
foo bar foo bar foo bar foo bar
914
.. _ctypes-callback-functions:
919
``ctypes`` allows to create C callable function pointers from Python callables.
920
These are sometimes called *callback functions*.
922
First, you must create a class for the callback function, the class knows the
923
calling convention, the return type, and the number and types of arguments this
924
function will receive.
926
The CFUNCTYPE factory function creates types for callback functions using the
927
normal cdecl calling convention, and, on Windows, the WINFUNCTYPE factory
928
function creates types for callback functions using the stdcall calling
931
Both of these factory functions are called with the result type as first
932
argument, and the callback functions expected argument types as the remaining
935
I will present an example here which uses the standard C library's :func:`qsort`
936
function, this is used to sort items with the help of a callback function.
937
:func:`qsort` will be used to sort an array of integers::
939
>>> IntArray5 = c_int * 5
940
>>> ia = IntArray5(5, 1, 7, 33, 99)
941
>>> qsort = libc.qsort
942
>>> qsort.restype = None
945
:func:`qsort` must be called with a pointer to the data to sort, the number of
946
items in the data array, the size of one item, and a pointer to the comparison
947
function, the callback. The callback will then be called with two pointers to
948
items, and it must return a negative integer if the first item is smaller than
949
the second, a zero if they are equal, and a positive integer else.
951
So our callback function receives pointers to integers, and must return an
952
integer. First we create the ``type`` for the callback function::
954
>>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
957
For the first implementation of the callback function, we simply print the
958
arguments we get, and return 0 (incremental development ;-)::
960
>>> def py_cmp_func(a, b):
961
... print "py_cmp_func", a, b
966
Create the C callable callback::
968
>>> cmp_func = CMPFUNC(py_cmp_func)
971
And we're ready to go::
973
>>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
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...>
983
py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
986
We know how to access the contents of a pointer, so lets redefine our callback::
988
>>> def py_cmp_func(a, b):
989
... print "py_cmp_func", a[0], b[0]
992
>>> cmp_func = CMPFUNC(py_cmp_func)
995
Here is what we get on Windows::
997
>>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
1010
It is funny to see that on linux the sort function seems to work much more
1011
efficient, it is doing less comparisons::
1013
>>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX
1021
Ah, we're nearly done! The last step is to actually compare the two items and
1022
return a useful result::
1024
>>> def py_cmp_func(a, b):
1025
... print "py_cmp_func", a[0], b[0]
1026
... return a[0] - b[0]
1030
Final run on Windows::
1032
>>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +WINDOWS
1047
>>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX
1055
It is quite interesting to see that the Windows :func:`qsort` function needs
1056
more comparisons than the linux version!
1058
As we can easily check, our array is sorted now::
1060
>>> for i in ia: print i,
1065
**Important note for callback functions:**
1067
Make sure you keep references to CFUNCTYPE objects as long as they are used from
1068
C code. ``ctypes`` doesn't, and if you don't, they may be garbage collected,
1069
crashing your program when a callback is made.
1072
.. _ctypes-accessing-values-exported-from-dlls:
1074
Accessing values exported from dlls
1075
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1077
Some shared libraries not only export functions, they also export variables. An
1078
example in the Python library itself is the ``Py_OptimizeFlag``, an integer set
1079
to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on
1082
``ctypes`` can access values like this with the :meth:`in_dll` class methods of
1083
the type. *pythonapi* is a predefined symbol giving access to the Python C
1086
>>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
1091
If the interpreter would have been started with :option:`-O`, the sample would
1092
have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been
1095
An extended example which also demonstrates the use of pointers accesses the
1096
``PyImport_FrozenModules`` pointer exported by Python.
1098
Quoting the Python docs: *This pointer is initialized to point to an array of
1099
"struct _frozen" records, terminated by one whose members are all NULL or zero.
1100
When a frozen module is imported, it is searched in this table. Third-party code
1101
could play tricks with this to provide a dynamically created collection of
1104
So manipulating this pointer could even prove useful. To restrict the example
1105
size, we show only how this table can be read with ``ctypes``::
1107
>>> from ctypes import *
1109
>>> class struct_frozen(Structure):
1110
... _fields_ = [("name", c_char_p),
1111
... ("code", POINTER(c_ubyte)),
1112
... ("size", c_int)]
1116
We have defined the ``struct _frozen`` data type, so we can get the pointer to
1119
>>> FrozenTable = POINTER(struct_frozen)
1120
>>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
1123
Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we
1124
can iterate over it, but we just have to make sure that our loop terminates,
1125
because pointers have no size. Sooner or later it would probably crash with an
1126
access violation or whatever, so it's better to break out of the loop when we
1127
hit the NULL entry::
1129
>>> for item in table:
1130
... print item.name, item.size
1131
... if item.name is None:
1140
The fact that standard Python has a frozen module and a frozen package
1141
(indicated by the negative size member) is not well known, it is only used for
1142
testing. Try it out with ``import __hello__`` for example.
1145
.. _ctypes-surprises:
1150
There are some edges in ``ctypes`` where you may be expect something else than
1151
what actually happens.
1153
Consider the following example::
1155
>>> from ctypes import *
1156
>>> class POINT(Structure):
1157
... _fields_ = ("x", c_int), ("y", c_int)
1159
>>> class RECT(Structure):
1160
... _fields_ = ("a", POINT), ("b", POINT)
1162
>>> p1 = POINT(1, 2)
1163
>>> p2 = POINT(3, 4)
1164
>>> rc = RECT(p1, p2)
1165
>>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
1167
>>> # now swap the two points
1168
>>> rc.a, rc.b = rc.b, rc.a
1169
>>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
1173
Hm. We certainly expected the last statement to print ``3 4 1 2``. What
1174
happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
1176
>>> temp0, temp1 = rc.b, rc.a
1181
Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of
1182
the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer
1183
contents of ``temp0`` into ``rc`` 's buffer. This, in turn, changes the
1184
contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have
1185
the expected effect.
1187
Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
1188
doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing
1189
the root-object's underlying buffer.
1191
Another example that may behave different from what one would expect is this::
1194
>>> s.value = "abc def ghi"
1197
>>> s.value is s.value
1201
Why is it printing ``False``? ctypes instances are objects containing a memory
1202
block plus some :term:`descriptor`\s accessing the contents of the memory.
1203
Storing a Python object in the memory block does not store the object itself,
1204
instead the ``contents`` of the object is stored. Accessing the contents again
1205
constructs a new Python object each time!
1208
.. _ctypes-variable-sized-data-types:
1210
Variable-sized data types
1211
^^^^^^^^^^^^^^^^^^^^^^^^^
1213
``ctypes`` provides some support for variable-sized arrays and structures (this
1214
was added in version 0.9.9.7).
1216
The ``resize`` function can be used to resize the memory buffer of an existing
1217
ctypes object. The function takes the object as first argument, and the
1218
requested size in bytes as the second argument. The memory block cannot be made
1219
smaller than the natural memory block specified by the objects type, a
1220
``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 ``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 ``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 ``ctypes.util`` module provides a function which can help to determine the
1276
.. data:: find_library(name)
1279
Try to find a library and return a pathname. *name* is the library name without
1280
any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this
1281
is the form used for the posix linker option :option:`-l`). If no library can
1282
be found, returns ``None``.
1284
The exact functionality is system dependent.
1286
On Linux, ``find_library`` tries to run external programs (/sbin/ldconfig, gcc,
1287
and objdump) to find the library file. It returns the filename of the library
1288
file. Here are some examples::
1290
>>> from ctypes.util import find_library
1291
>>> find_library("m")
1293
>>> find_library("c")
1295
>>> find_library("bz2")
1299
On OS X, ``find_library`` tries several predefined naming schemes and paths to
1300
locate the library, and returns a full pathname if successful::
1302
>>> from ctypes.util import find_library
1303
>>> find_library("c")
1304
'/usr/lib/libc.dylib'
1305
>>> find_library("m")
1306
'/usr/lib/libm.dylib'
1307
>>> find_library("bz2")
1308
'/usr/lib/libbz2.dylib'
1309
>>> find_library("AGL")
1310
'/System/Library/Frameworks/AGL.framework/AGL'
1313
On Windows, ``find_library`` searches along the system search path, and returns
1314
the full pathname, but since there is no predefined naming scheme a call like
1315
``find_library("c")`` will fail and return ``None``.
1317
If wrapping a shared library with ``ctypes``, it *may* be better to determine
1318
the shared library name at development type, and hardcode that into the wrapper
1319
module instead of using ``find_library`` to locate the library at runtime.
1322
.. _ctypes-loading-shared-libraries:
1324
Loading shared libraries
1325
^^^^^^^^^^^^^^^^^^^^^^^^
1327
There are several ways to loaded shared libraries into the Python process. One
1328
way is to instantiate one of the following classes:
1331
.. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
1333
Instances of this class represent loaded shared libraries. Functions in these
1334
libraries use the standard C calling convention, and are assumed to return
1338
.. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
1340
Windows only: Instances of this class represent loaded shared libraries,
1341
functions in these libraries use the ``stdcall`` calling convention, and are
1342
assumed to return the windows specific :class:`HRESULT` code. :class:`HRESULT`
1343
values contain information specifying whether the function call failed or
1344
succeeded, together with additional error code. If the return value signals a
1345
failure, an :class:`WindowsError` is automatically raised.
1348
.. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
1350
Windows only: Instances of this class represent loaded shared libraries,
1351
functions in these libraries use the ``stdcall`` calling convention, and are
1352
assumed to return ``int`` by default.
1354
On Windows CE only the standard calling convention is used, for convenience the
1355
:class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this
1358
The Python :term:`global interpreter lock` is released before calling any
1359
function exported by these libraries, and reacquired afterwards.
1362
.. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)
1364
Instances of this class behave like :class:`CDLL` instances, except that the
1365
Python GIL is *not* released during the function call, and after the function
1366
execution the Python error flag is checked. If the error flag is set, a Python
1367
exception is raised.
1369
Thus, this is only useful to call Python C api functions directly.
1371
All these classes can be instantiated by calling them with at least one
1372
argument, the pathname of the shared library. If you have an existing handle to
1373
an already loaded shard library, it can be passed as the ``handle`` named
1374
parameter, otherwise the underlying platforms ``dlopen`` or :meth:`LoadLibrary`
1375
function is used to load the library into the process, and to get a handle to
1378
The *mode* parameter can be used to specify how the library is loaded. For
1379
details, consult the ``dlopen(3)`` manpage, on Windows, *mode* is ignored.
1381
The *use_errno* parameter, when set to True, enables a ctypes
1382
mechanism that allows to access the system `errno` error number in a
1383
safe way. `ctypes` maintains a thread-local copy of the systems
1384
`errno` variable; if you call foreign functions created with
1385
`use_errno=True` then the `errno` value before the function call is
1386
swapped with the ctypes private copy, the same happens immediately
1387
after the function call.
1389
The function `ctypes.get_errno()` returns the value of the ctypes
1390
private copy, and the function `ctypes.set_errno(value)` changes the
1391
ctypes private copy to `value` and returns the former value.
1393
The *use_last_error* parameter, when set to True, enables the same
1394
mechanism for the Windows error code which is managed by the
1395
:func:`GetLastError` and :func:`SetLastError` Windows API functions;
1396
`ctypes.get_last_error()` and `ctypes.set_last_error(value)` are used
1397
to request and change the ctypes private copy of the windows error
1400
.. versionadded:: 2.6
1401
The ``use_last_error`` and ``use_errno`` optional parameters
1404
.. data:: RTLD_GLOBAL
1407
Flag to use as *mode* parameter. On platforms where this flag is not available,
1408
it is defined as the integer zero.
1411
.. data:: RTLD_LOCAL
1414
Flag to use as *mode* parameter. On platforms where this is not available, it
1415
is the same as *RTLD_GLOBAL*.
1418
.. data:: DEFAULT_MODE
1421
The default mode which is used to load shared libraries. On OSX 10.3, this is
1422
*RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*.
1424
Instances of these classes have no public methods, however :meth:`__getattr__`
1425
and :meth:`__getitem__` have special behavior: functions exported by the shared
1426
library can be accessed as attributes of by index. Please note that both
1427
:meth:`__getattr__` and :meth:`__getitem__` cache their result, so calling them
1428
repeatedly returns the same object each time.
1430
The following public attributes are available, their name starts with an
1431
underscore to not clash with exported function names:
1434
.. attribute:: PyDLL._handle
1436
The system handle used to access the library.
1439
.. attribute:: PyDLL._name
1441
The name of the library passed in the constructor.
1443
Shared libraries can also be loaded by using one of the prefabricated objects,
1444
which are instances of the :class:`LibraryLoader` class, either by calling the
1445
:meth:`LoadLibrary` method, or by retrieving the library as attribute of the
1449
.. class:: LibraryLoader(dlltype)
1451
Class which loads shared libraries. ``dlltype`` should be one of the
1452
:class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types.
1454
:meth:`__getattr__` has special behavior: It allows to load a shared library by
1455
accessing it as attribute of a library loader instance. The result is cached,
1456
so repeated attribute accesses return the same library each time.
1459
.. method:: LoadLibrary(name)
1461
Load a shared library into the process and return it. This method always
1462
returns a new instance of the library.
1464
These prefabricated library loaders are available:
1470
Creates :class:`CDLL` instances.
1476
Windows only: Creates :class:`WinDLL` instances.
1482
Windows only: Creates :class:`OleDLL` instances.
1488
Creates :class:`PyDLL` instances.
1490
For accessing the C Python api directly, a ready-to-use Python shared library
1491
object is available:
1497
An instance of :class:`PyDLL` that exposes Python C api functions as attributes.
1498
Note that all these functions are assumed to return C ``int``, which is of
1499
course not always the truth, so you have to assign the correct :attr:`restype`
1500
attribute to use these functions.
1503
.. _ctypes-foreign-functions:
1508
As explained in the previous section, foreign functions can be accessed as
1509
attributes of loaded shared libraries. The function objects created in this way
1510
by default accept any number of arguments, accept any ctypes data instances as
1511
arguments, and return the default result type specified by the library loader.
1512
They are instances of a private class:
1517
Base class for C callable foreign functions.
1519
Instances of foreign functions are also C compatible data types; they
1520
represent C function pointers.
1522
This behavior can be customized by assigning to special attributes of the
1523
foreign function object.
1526
.. attribute:: restype
1528
Assign a ctypes type to specify the result type of the foreign function.
1529
Use ``None`` for ``void`` a function not returning anything.
1531
It is possible to assign a callable Python object that is not a ctypes
1532
type, in this case the function is assumed to return a C ``int``, and the
1533
callable will be called with this integer, allowing to do further
1534
processing or error checking. Using this is deprecated, for more flexible
1535
post processing or error checking use a ctypes data type as
1536
:attr:`restype` and assign a callable to the :attr:`errcheck` attribute.
1539
.. attribute:: argtypes
1541
Assign a tuple of ctypes types to specify the argument types that the
1542
function accepts. Functions using the ``stdcall`` calling convention can
1543
only be called with the same number of arguments as the length of this
1544
tuple; functions using the C calling convention accept additional,
1545
unspecified arguments as well.
1547
When a foreign function is called, each actual argument is passed to the
1548
:meth:`from_param` class method of the items in the :attr:`argtypes`
1549
tuple, this method allows to adapt the actual argument to an object that
1550
the foreign function accepts. For example, a :class:`c_char_p` item in
1551
the :attr:`argtypes` tuple will convert a unicode string passed as
1552
argument into an byte string using ctypes conversion rules.
1554
New: It is now possible to put items in argtypes which are not ctypes
1555
types, but each item must have a :meth:`from_param` method which returns a
1556
value usable as argument (integer, string, ctypes instance). This allows
1557
to define adapters that can adapt custom objects as function parameters.
1560
.. attribute:: errcheck
1562
Assign a Python function or another callable to this attribute. The
1563
callable will be called with three or more arguments:
1565
.. function:: callable(result, func, arguments)
1568
``result`` is what the foreign function returns, as specified
1569
by the :attr:`restype` attribute.
1571
``func`` is the foreign function object itself, this allows
1572
to reuse the same callable object to check or post process
1573
the results of several functions.
1575
``arguments`` is a tuple containing the parameters originally
1576
passed to the function call, this allows to specialize the
1577
behavior on the arguments used.
1579
The object that this function returns will be returned from the
1580
foreign function call, but it can also check the result value
1581
and raise an exception if the foreign function call failed.
1584
.. exception:: ArgumentError()
1586
This exception is raised when a foreign function call cannot convert one of the
1590
.. _ctypes-function-prototypes:
1595
Foreign functions can also be created by instantiating function prototypes.
1596
Function prototypes are similar to function prototypes in C; they describe a
1597
function (return type, argument types, calling convention) without defining an
1598
implementation. The factory functions must be called with the desired result
1599
type and the argument types of the function.
1602
.. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
1604
The returned function prototype creates functions that use the standard C
1605
calling convention. The function will release the GIL during the call.
1606
If `use_errno` is set to True, the ctypes private copy of the system `errno`
1607
variable is exchanged with the real `errno` value bafore and after the call;
1608
`use_last_error` does the same for the Windows error code.
1610
.. versionchanged:: 2.6
1611
The optional `use_errno` and `use_last_error` parameters were
1615
.. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
1617
Windows only: The returned function prototype creates functions that use the
1618
``stdcall`` calling convention, except on Windows CE where :func:`WINFUNCTYPE`
1619
is the same as :func:`CFUNCTYPE`. The function will release the GIL during the
1620
call. `use_errno` and `use_last_error` have the 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 ``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 ``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, ``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
1794
instance of a ctypes type. ``offset`` defaults to zero, and must be
1795
an integer that will be 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.
1808
.. function:: cast(obj, type)
1810
This function is similar to the cast operator in C. It returns a new instance of
1811
``type`` which points to the same memory block as ``obj``. ``type`` must be a
1812
pointer type, and ``obj`` must be an object that can be interpreted as a
1816
.. function:: create_string_buffer(init_or_size[, size])
1818
This function creates a mutable character buffer. The returned object is a
1819
ctypes array of :class:`c_char`.
1821
``init_or_size`` must be an integer which specifies the size of the array, or a
1822
string which will be used to initialize the array items.
1824
If a string is specified as first argument, the buffer is made one item larger
1825
than the length of the string so that the last element in the array is a NUL
1826
termination character. An integer can be passed as second argument which allows
1827
to specify the size of the array if the length of the string should not be used.
1829
If the first parameter is a unicode string, it is converted into an 8-bit string
1830
according to ctypes conversion rules.
1833
.. function:: create_unicode_buffer(init_or_size[, size])
1835
This function creates a mutable unicode character buffer. The returned object is
1836
a ctypes array of :class:`c_wchar`.
1838
``init_or_size`` must be an integer which specifies the size of the array, or a
1839
unicode string which will be used to initialize the array items.
1841
If a unicode string is specified as first argument, the buffer is made one item
1842
larger than the length of the string so that the last element in the array is a
1843
NUL termination character. An integer can be passed as second argument which
1844
allows to specify the size of the array if the length of the string should not
1847
If the first parameter is a 8-bit string, it is converted into an unicode string
1848
according to ctypes conversion rules.
1851
.. function:: DllCanUnloadNow()
1853
Windows only: This function is a hook which allows to implement in-process COM
1854
servers with ctypes. It is called from the DllCanUnloadNow function that the
1855
_ctypes extension dll exports.
1858
.. function:: DllGetClassObject()
1860
Windows only: This function is a hook which allows to implement in-process COM
1861
servers with ctypes. It is called from the DllGetClassObject function that the
1862
``_ctypes`` extension dll exports.
1864
.. function:: find_library(name)
1865
:module: ctypes.util
1867
Try to find a library and return a pathname. `name` is the library name without
1868
any prefix like `lib`, suffix like ``.so``, ``.dylib`` or version number (this
1869
is the form used for the posix linker option :option:`-l`). If no library can
1870
be found, returns ``None``.
1872
The exact functionality is system dependent.
1874
.. versionchanged:: 2.6
1875
Windows only: ``find_library("m")`` or
1876
``find_library("c")`` return the result of a call to
1879
.. function:: find_msvcrt()
1880
:module: ctypes.util
1882
Windows only: return the filename of the VC runtype library used
1883
by Python, and by the extension modules. If the name of the
1884
library cannot be determined, ``None`` is returned.
1886
If you need to free memory, for example, allocated by an extension
1887
module with a call to the ``free(void *)``, it is important that you
1888
use the function in the same library that allocated the memory.
1890
.. versionadded:: 2.6
1892
.. function:: FormatError([code])
1894
Windows only: Returns a textual description of the error code. If no error code
1895
is specified, the last error code is used by calling the Windows api function
1899
.. function:: GetLastError()
1901
Windows only: Returns the last error code set by Windows in the calling thread.
1902
This function calls the Windows `GetLastError()` function directly,
1903
it does not return the ctypes-private copy of the error code.
1905
.. function:: get_errno()
1907
Returns the current value of the ctypes-private copy of the system
1908
`errno` variable in the calling thread.
1910
.. versionadded:: 2.6
1912
.. function:: get_last_error()
1914
Windows only: returns the current value of the ctypes-private copy of the system
1915
`LastError` variable in the calling thread.
1917
.. versionadded:: 2.6
1919
.. function:: memmove(dst, src, count)
1921
Same as the standard C memmove library function: copies *count* bytes from
1922
``src`` to *dst*. *dst* and ``src`` must be integers or ctypes instances that
1923
can be converted to pointers.
1926
.. function:: memset(dst, c, count)
1928
Same as the standard C memset library function: fills the memory block at
1929
address *dst* with *count* bytes of value *c*. *dst* must be an integer
1930
specifying an address, or a ctypes instance.
1933
.. function:: POINTER(type)
1935
This factory function creates and returns a new ctypes pointer type. Pointer
1936
types are cached an reused internally, so calling this function repeatedly is
1937
cheap. type must be a ctypes type.
1940
.. function:: pointer(obj)
1942
This function creates a new pointer instance, pointing to ``obj``. The returned
1943
object is of the type POINTER(type(obj)).
1945
Note: If you just want to pass a pointer to an object to a foreign function
1946
call, you should use ``byref(obj)`` which is much faster.
1949
.. function:: resize(obj, size)
1951
This function resizes the internal memory buffer of obj, which must be an
1952
instance of a ctypes type. It is not possible to make the buffer smaller than
1953
the native size of the objects type, as given by sizeof(type(obj)), but it is
1954
possible to enlarge the buffer.
1957
.. function:: set_conversion_mode(encoding, errors)
1959
This function sets the rules that ctypes objects use when converting between
1960
8-bit strings and unicode strings. encoding must be a string specifying an
1961
encoding, like ``'utf-8'`` or ``'mbcs'``, errors must be a string specifying the
1962
error handling on encoding/decoding errors. Examples of possible values are
1963
``"strict"``, ``"replace"``, or ``"ignore"``.
1965
``set_conversion_mode`` returns a 2-tuple containing the previous conversion
1966
rules. On windows, the initial conversion rules are ``('mbcs', 'ignore')``, on
1967
other systems ``('ascii', 'strict')``.
1970
.. function:: set_errno(value)
1972
Set the current value of the ctypes-private copy of the system
1973
`errno` variable in the calling thread to `value` and return the
1976
.. versionadded:: 2.6
1978
.. function:: set_last_error(value)
1980
Windows only: set the current value of the ctypes-private copy of
1981
the system `LastError` variable in the calling thread to `value`
1982
and return the previous value.
1984
.. versionadded:: 2.6
1986
.. function:: sizeof(obj_or_type)
1988
Returns the size in bytes of a ctypes type or instance memory buffer. Does the
1989
same as the C ``sizeof()`` function.
1992
.. function:: string_at(address[, size])
1994
This function returns the string starting at memory address address. If size
1995
is specified, it is used as size, otherwise the string is assumed to be
1999
.. function:: WinError(code=None, descr=None)
2001
Windows only: this function is probably the worst-named thing in ctypes. It
2002
creates an instance of WindowsError. If *code* is not specified,
2003
``GetLastError`` is called to determine the error code. If ``descr`` is not
2004
specified, :func:`FormatError` is called to get a textual description of the
2008
.. function:: wstring_at(address)
2010
This function returns the wide character string starting at memory address
2011
``address`` as unicode string. If ``size`` is specified, it is used as the
2012
number of characters of the string, otherwise the string is assumed to be
2016
.. _ctypes-data-types:
2024
This non-public class is the common base class of all ctypes data types. Among
2025
other things, all ctypes type instances contain a memory block that hold C
2026
compatible data; the address of the memory block is returned by the
2027
``addressof()`` helper function. Another instance variable is exposed as
2028
:attr:`_objects`; this contains other Python objects that need to be kept alive
2029
in case the memory block contains pointers.
2031
Common methods of ctypes data types, these are all class methods (to be
2032
exact, they are methods of the :term:`metaclass`):
2035
.. method:: _CData.from_buffer(source[, offset])
2037
This method returns a ctypes instance that shares the buffer of
2038
the ``source`` object. The ``source`` object must support the
2039
writeable buffer interface. The optional ``offset`` parameter
2040
specifies an offset into the source buffer in bytes; the default
2041
is zero. If the source buffer is not large enough a ValueError
2044
.. versionadded:: 2.6
2046
.. method:: _CData.from_buffer_copy(source[, offset])
2048
This method creates a ctypes instance, copying the buffer from
2049
the source object buffer which must be readable. The optional
2050
``offset`` parameter specifies an offset into the source buffer
2051
in bytes; the default is zero. If the source buffer is not
2052
large enough a ValueError is raised.
2054
.. versionadded:: 2.6
2057
.. method:: from_address(address)
2059
This method returns a ctypes type instance using the memory specified by
2060
address which must be an integer.
2063
.. method:: from_param(obj)
2065
This method adapts *obj* to a ctypes type. It is called with the actual
2066
object used in a foreign function call when the type is present in the
2067
foreign function's :attr:`argtypes` tuple; it must return an object that
2068
can be used as a function call parameter.
2070
All ctypes data types have a default implementation of this classmethod
2071
that normally returns ``obj`` if that is an instance of the type. Some
2072
types accept other objects as well.
2075
.. method:: in_dll(library, name)
2077
This method returns a ctypes type instance exported by a shared
2078
library. *name* is the name of the symbol that exports the data, *library*
2079
is the loaded shared library.
2082
Common instance variables of ctypes data types:
2085
.. attribute:: _b_base_
2087
Sometimes ctypes data instances do not own the memory block they contain,
2088
instead they share part of the memory block of a base object. The
2089
:attr:`_b_base_` read-only member is the root ctypes object that owns the
2093
.. attribute:: _b_needsfree_
2095
This read-only variable is true when the ctypes data instance has
2096
allocated the memory block itself, false otherwise.
2099
.. attribute:: _objects
2101
This member is either ``None`` or a dictionary containing Python objects
2102
that need to be kept alive so that the memory block contents is kept
2103
valid. This object is only exposed for debugging; never modify the
2104
contents of this dictionary.
2107
.. _ctypes-fundamental-data-types-2:
2109
Fundamental data types
2110
^^^^^^^^^^^^^^^^^^^^^^
2113
.. class:: _SimpleCData
2115
This non-public class is the base class of all fundamental ctypes data types. It
2116
is mentioned here because it contains the common attributes of the fundamental
2117
ctypes data types. ``_SimpleCData`` is a subclass of ``_CData``, so it inherits
2118
their methods and attributes.
2120
.. versionchanged:: 2.6
2121
ctypes data types that are not and do not contain pointers can
2124
Instances have a single attribute:
2127
.. attribute:: value
2129
This attribute contains the actual value of the instance. For integer and
2130
pointer types, it is an integer, for character types, it is a single
2131
character string, for character pointer types it is a Python string or
2134
When the ``value`` attribute is retrieved from a ctypes instance, usually
2135
a new object is returned each time. ``ctypes`` does *not* implement
2136
original object return, always a new object is constructed. The same is
2137
true for all other ctypes object instances.
2139
Fundamental data types, when returned as foreign function call results, or, for
2140
example, by retrieving structure field members or array items, are transparently
2141
converted to native Python types. In other words, if a foreign function has a
2142
:attr:`restype` of :class:`c_char_p`, you will always receive a Python string,
2143
*not* a :class:`c_char_p` instance.
2145
Subclasses of fundamental data types do *not* inherit this behavior. So, if a
2146
foreign functions :attr:`restype` is a subclass of :class:`c_void_p`, you will
2147
receive an instance of this subclass from the function call. Of course, you can
2148
get the value of the pointer by accessing the ``value`` attribute.
2150
These are the fundamental ctypes data types:
2155
Represents the C signed char datatype, and interprets the value as small
2156
integer. The constructor accepts an optional integer initializer; no overflow
2162
Represents the C char datatype, and interprets the value as a single character.
2163
The constructor accepts an optional string initializer, the length of the string
2164
must be exactly one character.
2169
Represents the C char \* datatype, which must be a pointer to a zero-terminated
2170
string. The constructor accepts an integer address, or a string.
2175
Represents the C double datatype. The constructor accepts an optional float
2179
.. class:: c_longdouble
2181
Represents the C long double datatype. The constructor accepts an
2182
optional float initializer. On platforms where ``sizeof(long
2183
double) == sizeof(double)`` it is an alias to :class:`c_double`.
2185
.. versionadded:: 2.6
2189
Represents the C float datatype. The constructor accepts an optional float
2195
Represents the C signed int datatype. The constructor accepts an optional
2196
integer initializer; no overflow checking is done. On platforms where
2197
``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`.
2202
Represents the C 8-bit ``signed int`` datatype. Usually an alias for
2208
Represents the C 16-bit signed int datatype. Usually an alias for
2214
Represents the C 32-bit signed int datatype. Usually an alias for
2220
Represents the C 64-bit ``signed int`` datatype. Usually an alias for
2221
:class:`c_longlong`.
2226
Represents the C ``signed long`` datatype. The constructor accepts an optional
2227
integer initializer; no overflow checking is done.
2230
.. class:: c_longlong
2232
Represents the C ``signed long long`` datatype. The constructor accepts an
2233
optional integer initializer; no overflow checking is done.
2238
Represents the C ``signed short`` datatype. The constructor accepts an optional
2239
integer initializer; no overflow checking is done.
2244
Represents the C ``size_t`` datatype.
2249
Represents the C ``unsigned char`` datatype, it interprets the value as small
2250
integer. The constructor accepts an optional integer initializer; no overflow
2256
Represents the C ``unsigned int`` datatype. The constructor accepts an optional
2257
integer initializer; no overflow checking is done. On platforms where
2258
``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`.
2263
Represents the C 8-bit unsigned int datatype. Usually an alias for
2269
Represents the C 16-bit unsigned int datatype. Usually an alias for
2275
Represents the C 32-bit unsigned int datatype. Usually an alias for
2281
Represents the C 64-bit unsigned int datatype. Usually an alias for
2282
:class:`c_ulonglong`.
2287
Represents the C ``unsigned long`` datatype. The constructor accepts an optional
2288
integer initializer; no overflow checking is done.
2291
.. class:: c_ulonglong
2293
Represents the C ``unsigned long long`` datatype. The constructor accepts an
2294
optional integer initializer; no overflow checking is done.
2299
Represents the C ``unsigned short`` datatype. The constructor accepts an
2300
optional integer initializer; no overflow checking is done.
2305
Represents the C ``void *`` type. The value is represented as integer. The
2306
constructor accepts an optional integer initializer.
2311
Represents the C ``wchar_t`` datatype, and interprets the value as a single
2312
character unicode string. The constructor accepts an optional string
2313
initializer, the length of the string must be exactly one character.
2316
.. class:: c_wchar_p
2318
Represents the C ``wchar_t *`` datatype, which must be a pointer to a
2319
zero-terminated wide character string. The constructor accepts an integer
2320
address, or a string.
2325
Represent the C ``bool`` datatype (more accurately, _Bool from C99). Its value
2326
can be True or False, and the constructor accepts any object that has a truth
2329
.. versionadded:: 2.6
2334
Windows only: Represents a :class:`HRESULT` value, which contains success or
2335
error information for a function or method call.
2338
.. class:: py_object
2340
Represents the C ``PyObject *`` datatype. Calling this without an argument
2341
creates a ``NULL`` ``PyObject *`` pointer.
2343
The ``ctypes.wintypes`` module provides quite some other Windows specific data
2344
types, for example ``HWND``, ``WPARAM``, or ``DWORD``. Some useful structures
2345
like ``MSG`` or ``RECT`` are also defined.
2348
.. _ctypes-structured-data-types:
2350
Structured data types
2351
^^^^^^^^^^^^^^^^^^^^^
2354
.. class:: Union(*args, **kw)
2356
Abstract base class for unions in native byte order.
2359
.. class:: BigEndianStructure(*args, **kw)
2361
Abstract base class for structures in *big endian* byte order.
2364
.. class:: LittleEndianStructure(*args, **kw)
2366
Abstract base class for structures in *little endian* byte order.
2368
Structures with non-native byte order cannot contain pointer type fields, or any
2369
other data types containing pointer type fields.
2372
.. class:: Structure(*args, **kw)
2374
Abstract base class for structures in *native* byte order.
2376
Concrete structure and union types must be created by subclassing one of these
2377
types, and at least define a :attr:`_fields_` class variable. ``ctypes`` will
2378
create :term:`descriptor`\s which allow reading and writing the fields by direct
2379
attribute accesses. These are the
2382
.. attribute:: _fields_
2384
A sequence defining the structure fields. The items must be 2-tuples or
2385
3-tuples. The first item is the name of the field, the second item
2386
specifies the type of the field; it can be any ctypes data type.
2388
For integer type fields like :class:`c_int`, a third optional item can be
2389
given. It must be a small positive integer defining the bit width of the
2392
Field names must be unique within one structure or union. This is not
2393
checked, only one field can be accessed when names are repeated.
2395
It is possible to define the :attr:`_fields_` class variable *after* the
2396
class statement that defines the Structure subclass, this allows to create
2397
data types that directly or indirectly reference themselves::
2399
class List(Structure):
2401
List._fields_ = [("pnext", POINTER(List)),
2405
The :attr:`_fields_` class variable must, however, be defined before the
2406
type is first used (an instance is created, ``sizeof()`` is called on it,
2407
and so on). Later assignments to the :attr:`_fields_` class variable will
2408
raise an AttributeError.
2410
Structure and union subclass constructors accept both positional and named
2411
arguments. Positional arguments are used to initialize the fields in the
2412
same order as they appear in the :attr:`_fields_` definition, named
2413
arguments are used to initialize the fields with the corresponding name.
2415
It is possible to defined sub-subclasses of structure types, they inherit
2416
the fields of the base class plus the :attr:`_fields_` defined in the
2417
sub-subclass, if any.
2420
.. attribute:: _pack_
2422
An optional small integer that allows to override the alignment of
2423
structure fields in the instance. :attr:`_pack_` must already be defined
2424
when :attr:`_fields_` is assigned, otherwise it will have no effect.
2427
.. attribute:: _anonymous_
2429
An optional sequence that lists the names of unnamed (anonymous) fields.
2430
``_anonymous_`` must be already defined when :attr:`_fields_` is assigned,
2431
otherwise it will have no effect.
2433
The fields listed in this variable must be structure or union type fields.
2434
``ctypes`` will create descriptors in the structure type that allows to
2435
access the nested fields directly, without the need to create the
2436
structure or union field.
2438
Here is an example type (Windows)::
2441
_fields_ = [("lptdesc", POINTER(TYPEDESC)),
2442
("lpadesc", POINTER(ARRAYDESC)),
2443
("hreftype", HREFTYPE)]
2445
class TYPEDESC(Structure):
2446
_fields_ = [("u", _U),
2449
_anonymous_ = ("u",)
2451
The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field
2452
specifies which one of the union fields is valid. Since the ``u`` field
2453
is defined as anonymous field, it is now possible to access the members
2454
directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc``
2455
are equivalent, but the former is faster since it does not need to create
2456
a temporary union instance::
2460
td.lptdesc = POINTER(some_type)
2461
td.u.lptdesc = POINTER(some_type)
2463
It is possible to defined sub-subclasses of structures, they inherit the fields
2464
of the base class. If the subclass definition has a separate :attr:`_fields_`
2465
variable, the fields specified in this are appended to the fields of the base
2468
Structure and union constructors accept both positional and keyword arguments.
2469
Positional arguments are used to initialize member fields in the same order as
2470
they are appear in :attr:`_fields_`. Keyword arguments in the constructor are
2471
interpreted as attribute assignments, so they will initialize :attr:`_fields_`
2472
with the same name, or create new attributes for names not present in
2476
.. _ctypes-arrays-pointers:
2481
Not yet written - please see the sections :ref:`ctypes-pointers` and
2482
section :ref:`ctypes-arrays` in the tutorial.