~malept/ubuntu/lucid/python2.6/dev-dependency-fix

« back to all changes in this revision

Viewing changes to Doc/library/ctypes.rst

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2009-02-13 12:51:00 UTC
  • Revision ID: james.westby@ubuntu.com-20090213125100-uufgcb9yeqzujpqw
Tags: upstream-2.6.1
ImportĀ upstreamĀ versionĀ 2.6.1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
 
 
2
:mod:`ctypes` --- A foreign function library for Python.
 
3
========================================================
 
4
 
 
5
.. module:: ctypes
 
6
   :synopsis: A foreign function library for Python.
 
7
.. moduleauthor:: Thomas Heller <theller@python.net>
 
8
 
 
9
 
 
10
.. versionadded:: 2.5
 
11
 
 
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.
 
15
 
 
16
 
 
17
.. _ctypes-ctypes-tutorial:
 
18
 
 
19
ctypes tutorial
 
20
---------------
 
21
 
 
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.
 
25
 
 
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.
 
30
 
 
31
 
 
32
.. _ctypes-loading-dynamic-link-libraries:
 
33
 
 
34
Loading dynamic link libraries
 
35
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
36
 
 
37
``ctypes`` exports the *cdll*, and on Windows *windll* and *oledll*
 
38
objects, for loading dynamic link libraries.
 
39
 
 
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.
 
47
 
 
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
 
50
convention::
 
51
 
 
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
 
58
   >>>
 
59
 
 
60
Windows appends the usual ``.dll`` file suffix automatically.
 
61
 
 
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::
 
66
 
 
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 ...>
 
72
   >>>
 
73
 
 
74
.. XXX Add section for Mac OS X.
 
75
 
 
76
 
 
77
.. _ctypes-accessing-functions-from-loaded-dlls:
 
78
 
 
79
Accessing functions from loaded dlls
 
80
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
81
 
 
82
Functions are accessed as attributes of dll objects::
 
83
 
 
84
   >>> from ctypes import *
 
85
   >>> libc.printf
 
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
 
95
   >>>
 
96
 
 
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::
 
104
 
 
105
   /* ANSI version */
 
106
   HMODULE GetModuleHandleA(LPCSTR lpModuleName);
 
107
   /* UNICODE version */
 
108
   HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
 
109
 
 
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
 
113
respectively.
 
114
 
 
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::
 
118
 
 
119
   >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") # doctest: +WINDOWS
 
120
   <_FuncPtr object at 0x...>
 
121
   >>>
 
122
 
 
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::
 
125
 
 
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
 
134
   >>>
 
135
 
 
136
 
 
137
.. _ctypes-calling-functions:
 
138
 
 
139
Calling functions
 
140
^^^^^^^^^^^^^^^^^
 
141
 
 
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
 
145
handle.
 
146
 
 
147
This example calls both functions with a NULL pointer (``None`` should be used
 
148
as the NULL pointer)::
 
149
 
 
150
   >>> print libc.time(None) # doctest: +SKIP
 
151
   1150640792
 
152
   >>> print hex(windll.kernel32.GetModuleHandleA(None)) # doctest: +WINDOWS
 
153
   0x1d000000
 
154
   >>>
 
155
 
 
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::
 
160
 
 
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)
 
169
   >>>
 
170
 
 
171
The same exception is raised when you call an ``stdcall`` function with the
 
172
``cdecl`` calling convention, or vice versa::
 
173
 
 
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)
 
178
   >>>
 
179
 
 
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)
 
184
   >>>
 
185
 
 
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.
 
188
 
 
189
On Windows, ``ctypes`` uses win32 structured exception handling to prevent
 
190
crashes from general protection faults when functions are called with invalid
 
191
argument values::
 
192
 
 
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
 
197
   >>>
 
198
 
 
199
There are, however, enough ways to crash Python with ``ctypes``, so you should
 
200
be careful anyway.
 
201
 
 
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.
 
208
 
 
209
Before we move on calling functions with other parameter types, we have to learn
 
210
more about ``ctypes`` data types.
 
211
 
 
212
 
 
213
.. _ctypes-fundamental-data-types:
 
214
 
 
215
Fundamental data types
 
216
^^^^^^^^^^^^^^^^^^^^^^
 
217
 
 
218
``ctypes`` defines a number of primitive C compatible data types :
 
219
 
 
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
   +----------------------+--------------------------------+----------------------------+
 
260
 
 
261
 
 
262
All these types can be created by calling them with an optional initializer of
 
263
the correct type and value::
 
264
 
 
265
   >>> c_int()
 
266
   c_long(0)
 
267
   >>> c_char_p("Hello, World")
 
268
   c_char_p('Hello, World')
 
269
   >>> c_ushort(-3)
 
270
   c_ushort(65533)
 
271
   >>>
 
272
 
 
273
Since these types are mutable, their value can also be changed afterwards::
 
274
 
 
275
   >>> i = c_int(42)
 
276
   >>> print i
 
277
   c_long(42)
 
278
   >>> print i.value
 
279
   42
 
280
   >>> i.value = -99
 
281
   >>> print i.value
 
282
   -99
 
283
   >>>
 
284
 
 
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)::
 
289
 
 
290
   >>> s = "Hello, World"
 
291
   >>> c_s = c_char_p(s)
 
292
   >>> print c_s
 
293
   c_char_p('Hello, World')
 
294
   >>> c_s.value = "Hi, there"
 
295
   >>> print c_s
 
296
   c_char_p('Hi, there')
 
297
   >>> print s                 # first string is unchanged
 
298
   Hello, World
 
299
   >>>
 
300
 
 
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``
 
306
property::
 
307
 
 
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)
 
311
   3 '\x00\x00\x00'
 
312
   >>> p = create_string_buffer("Hello")      # create a buffer containing a NUL terminated string
 
313
   >>> print sizeof(p), repr(p.raw)
 
314
   6 'Hello\x00'
 
315
   >>> print repr(p.value)
 
316
   'Hello'
 
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'
 
320
   >>> p.value = "Hi"
 
321
   >>> print sizeof(p), repr(p.raw)
 
322
   10 'Hi\x00lo\x00\x00\x00\x00\x00'
 
323
   >>>
 
324
 
 
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.
 
329
 
 
330
 
 
331
.. _ctypes-calling-functions-continued:
 
332
 
 
333
Calling functions, continued
 
334
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
335
 
 
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*::
 
339
 
 
340
   >>> printf = libc.printf
 
341
   >>> printf("Hello, %s\n", "World!")
 
342
   Hello, World!
 
343
   14
 
344
   >>> printf("Hello, %S", u"World!")
 
345
   Hello, World!
 
346
   13
 
347
   >>> printf("%d bottles of beer\n", 42)
 
348
   42 bottles of beer
 
349
   19
 
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
 
354
   >>>
 
355
 
 
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::
 
359
 
 
360
   >>> printf("An int %d, a double %f\n", 1234, c_double(3.14))
 
361
   Integer 1234, double 3.1400001049
 
362
   31
 
363
   >>>
 
364
 
 
365
 
 
366
.. _ctypes-calling-functions-with-own-custom-data-types:
 
367
 
 
368
Calling functions with your own custom data types
 
369
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
370
 
 
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::
 
375
 
 
376
   >>> class Bottles(object):
 
377
   ...     def __init__(self, number):
 
378
   ...         self._as_parameter_ = number
 
379
   ...
 
380
   >>> bottles = Bottles(42)
 
381
   >>> printf("%d bottles of beer\n", bottles)
 
382
   42 bottles of beer
 
383
   19
 
384
   >>>
 
385
 
 
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
 
388
available.
 
389
 
 
390
 
 
391
.. _ctypes-specifying-required-argument-types:
 
392
 
 
393
Specifying the required argument types (function prototypes)
 
394
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
395
 
 
396
It is possible to specify the required argument types of functions exported from
 
397
DLLs by setting the :attr:`argtypes` attribute.
 
398
 
 
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)::
 
403
 
 
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
 
407
   37
 
408
   >>>
 
409
 
 
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::
 
412
 
 
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)
 
418
   X 2 3.00000012
 
419
   12
 
420
   >>>
 
421
 
 
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.
 
431
 
 
432
 
 
433
.. _ctypes-return-types:
 
434
 
 
435
Return types
 
436
^^^^^^^^^^^^
 
437
 
 
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
 
440
object.
 
441
 
 
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::
 
444
 
 
445
   >>> strchr = libc.strchr
 
446
   >>> strchr("abcdef", ord("d")) # doctest: +SKIP
 
447
   8059983
 
448
   >>> strchr.restype = c_char_p # c_char_p is a pointer to a string
 
449
   >>> strchr("abcdef", ord("d"))
 
450
   'def'
 
451
   >>> print strchr("abcdef", ord("x"))
 
452
   None
 
453
   >>>
 
454
 
 
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::
 
458
 
 
459
   >>> strchr.restype = c_char_p
 
460
   >>> strchr.argtypes = [c_char_p, c_char]
 
461
   >>> strchr("abcdef", "d")
 
462
   'def'
 
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")
 
468
   None
 
469
   >>> strchr("abcdef", "d")
 
470
   'def'
 
471
   >>>
 
472
 
 
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::
 
478
 
 
479
   >>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
 
480
   >>> def ValidHandle(value):
 
481
   ...     if value == 0:
 
482
   ...         raise WinError()
 
483
   ...     return value
 
484
   ...
 
485
   >>>
 
486
   >>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS
 
487
   >>> GetModuleHandle(None) # doctest: +WINDOWS
 
488
   486539264
 
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.
 
494
   >>>
 
495
 
 
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.
 
500
 
 
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.
 
503
 
 
504
 
 
505
.. _ctypes-passing-pointers:
 
506
 
 
507
Passing pointers (or: passing parameters by reference)
 
508
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
509
 
 
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*.
 
513
 
 
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::
 
519
 
 
520
   >>> i = c_int()
 
521
   >>> f = c_float()
 
522
   >>> s = create_string_buffer('\000' * 32)
 
523
   >>> print i.value, f.value, repr(s.value)
 
524
   0 0.0 ''
 
525
   >>> libc.sscanf("1 3.14 Hello", "%d %f %s",
 
526
   ...             byref(i), byref(f), s)
 
527
   3
 
528
   >>> print i.value, f.value, repr(s.value)
 
529
   1 3.1400001049 'Hello'
 
530
   >>>
 
531
 
 
532
 
 
533
.. _ctypes-structures-unions:
 
534
 
 
535
Structures and unions
 
536
^^^^^^^^^^^^^^^^^^^^^
 
537
 
 
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*.
 
542
 
 
543
The field type must be a ``ctypes`` type like :class:`c_int`, or any other
 
544
derived ``ctypes`` type: structure, union, array, pointer.
 
545
 
 
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
 
548
constructor::
 
549
 
 
550
   >>> from ctypes import *
 
551
   >>> class POINT(Structure):
 
552
   ...     _fields_ = [("x", c_int),
 
553
   ...                 ("y", c_int)]
 
554
   ...
 
555
   >>> point = POINT(10, 20)
 
556
   >>> print point.x, point.y
 
557
   10 20
 
558
   >>> point = POINT(y=5)
 
559
   >>> print point.x, point.y
 
560
   0 5
 
561
   >>> POINT(1, 2, 3)
 
562
   Traceback (most recent call last):
 
563
     File "<stdin>", line 1, in ?
 
564
   ValueError: too many initializers
 
565
   >>>
 
566
 
 
567
You can, however, build much more complicated structures. Structures can itself
 
568
contain other structures by using a structure as a field type.
 
569
 
 
570
Here is a RECT structure which contains two POINTs named ``upperleft`` and
 
571
``lowerright``  ::
 
572
 
 
573
   >>> class RECT(Structure):
 
574
   ...     _fields_ = [("upperleft", POINT),
 
575
   ...                 ("lowerright", POINT)]
 
576
   ...
 
577
   >>> rc = RECT(point)
 
578
   >>> print rc.upperleft.x, rc.upperleft.y
 
579
   0 5
 
580
   >>> print rc.lowerright.x, rc.lowerright.y
 
581
   0 0
 
582
   >>>
 
583
 
 
584
Nested structures can also be initialized in the constructor in several ways::
 
585
 
 
586
   >>> r = RECT(POINT(1, 2), POINT(3, 4))
 
587
   >>> r = RECT((1, 2), (3, 4))
 
588
 
 
589
Field :term:`descriptor`\s can be retrieved from the *class*, they are useful
 
590
for debugging because they can provide useful information::
 
591
 
 
592
   >>> print POINT.x
 
593
   <Field type=c_long, ofs=0, size=4>
 
594
   >>> print POINT.y
 
595
   <Field type=c_long, ofs=4, size=4>
 
596
   >>>
 
597
 
 
598
 
 
599
.. _ctypes-structureunion-alignment-byte-order:
 
600
 
 
601
Structure/union alignment and byte order
 
602
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
603
 
 
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.
 
609
 
 
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.
 
614
 
 
615
 
 
616
.. _ctypes-bit-fields-in-structures-unions:
 
617
 
 
618
Bit fields in structures and unions
 
619
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
620
 
 
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::
 
624
 
 
625
   >>> class Int(Structure):
 
626
   ...     _fields_ = [("first_16", c_int, 16),
 
627
   ...                 ("second_16", c_int, 16)]
 
628
   ...
 
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>
 
633
   >>>
 
634
 
 
635
 
 
636
.. _ctypes-arrays:
 
637
 
 
638
Arrays
 
639
^^^^^^
 
640
 
 
641
Arrays are sequences, containing a fixed number of instances of the same type.
 
642
 
 
643
The recommended way to create array types is by multiplying a data type with a
 
644
positive integer::
 
645
 
 
646
   TenPointsArrayType = POINT * 10
 
647
 
 
648
Here is an example of an somewhat artificial data type, a structure containing 4
 
649
POINTs among other stuff::
 
650
 
 
651
   >>> from ctypes import *
 
652
   >>> class POINT(Structure):
 
653
   ...    _fields_ = ("x", c_int), ("y", c_int)
 
654
   ...
 
655
   >>> class MyStruct(Structure):
 
656
   ...    _fields_ = [("a", c_int),
 
657
   ...                ("b", c_float),
 
658
   ...                ("point_array", POINT * 4)]
 
659
   >>>
 
660
   >>> print len(MyStruct().point_array)
 
661
   4
 
662
   >>>
 
663
 
 
664
Instances are created in the usual way, by calling the class::
 
665
 
 
666
   arr = TenPointsArrayType()
 
667
   for pt in arr:
 
668
       print pt.x, pt.y
 
669
 
 
670
The above code print a series of ``0 0`` lines, because the array contents is
 
671
initialized to zeros.
 
672
 
 
673
Initializers of the correct type can also be specified::
 
674
 
 
675
   >>> from ctypes import *
 
676
   >>> TenIntegers = c_int * 10
 
677
   >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
 
678
   >>> print ii
 
679
   <c_long_Array_10 object at 0x...>
 
680
   >>> for i in ii: print i,
 
681
   ...
 
682
   1 2 3 4 5 6 7 8 9 10
 
683
   >>>
 
684
 
 
685
 
 
686
.. _ctypes-pointers:
 
687
 
 
688
Pointers
 
689
^^^^^^^^
 
690
 
 
691
Pointer instances are created by calling the ``pointer`` function on a
 
692
``ctypes`` type::
 
693
 
 
694
   >>> from ctypes import *
 
695
   >>> i = c_int(42)
 
696
   >>> pi = pointer(i)
 
697
   >>>
 
698
 
 
699
Pointer instances have a ``contents`` attribute which returns the object to
 
700
which the pointer points, the ``i`` object above::
 
701
 
 
702
   >>> pi.contents
 
703
   c_long(42)
 
704
   >>>
 
705
 
 
706
Note that ``ctypes`` does not have OOR (original object return), it constructs a
 
707
new, equivalent object each time you retrieve an attribute::
 
708
 
 
709
   >>> pi.contents is i
 
710
   False
 
711
   >>> pi.contents is pi.contents
 
712
   False
 
713
   >>>
 
714
 
 
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::
 
717
 
 
718
   >>> i = c_int(99)
 
719
   >>> pi.contents = i
 
720
   >>> pi.contents
 
721
   c_long(99)
 
722
   >>>
 
723
 
 
724
.. XXX Document dereferencing pointers, and that it is preferred over the .contents attribute.
 
725
 
 
726
Pointer instances can also be indexed with integers::
 
727
 
 
728
   >>> pi[0]
 
729
   99
 
730
   >>>
 
731
 
 
732
Assigning to an integer index changes the pointed to value::
 
733
 
 
734
   >>> print i
 
735
   c_long(99)
 
736
   >>> pi[0] = 22
 
737
   >>> print i
 
738
   c_long(22)
 
739
   >>>
 
740
 
 
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
 
745
item.
 
746
 
 
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
 
750
type::
 
751
 
 
752
   >>> PI = POINTER(c_int)
 
753
   >>> PI
 
754
   <class 'ctypes.LP_c_long'>
 
755
   >>> PI(42)
 
756
   Traceback (most recent call last):
 
757
     File "<stdin>", line 1, in ?
 
758
   TypeError: expected c_long instead of int
 
759
   >>> PI(c_int(42))
 
760
   <ctypes.LP_c_long object at 0x...>
 
761
   >>>
 
762
 
 
763
Calling the pointer type without an argument creates a ``NULL`` pointer.
 
764
``NULL`` pointers have a ``False`` boolean value::
 
765
 
 
766
   >>> null_ptr = POINTER(c_int)()
 
767
   >>> print bool(null_ptr)
 
768
   False
 
769
   >>>
 
770
 
 
771
``ctypes`` checks for ``NULL`` when dereferencing pointers (but dereferencing
 
772
invalid non-\ ``NULL`` pointers would crash Python)::
 
773
 
 
774
   >>> null_ptr[0]
 
775
   Traceback (most recent call last):
 
776
       ....
 
777
   ValueError: NULL pointer access
 
778
   >>>
 
779
 
 
780
   >>> null_ptr[0] = 1234
 
781
   Traceback (most recent call last):
 
782
       ....
 
783
   ValueError: NULL pointer access
 
784
   >>>
 
785
 
 
786
 
 
787
.. _ctypes-type-conversions:
 
788
 
 
789
Type conversions
 
790
^^^^^^^^^^^^^^^^
 
791
 
 
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::
 
798
 
 
799
   >>> class Bar(Structure):
 
800
   ...     _fields_ = [("count", c_int), ("values", POINTER(c_int))]
 
801
   ...
 
802
   >>> bar = Bar()
 
803
   >>> bar.values = (c_int * 3)(1, 2, 3)
 
804
   >>> bar.count = 3
 
805
   >>> for i in range(bar.count):
 
806
   ...     print bar.values[i]
 
807
   ...
 
808
   1
 
809
   2
 
810
   3
 
811
   >>>
 
812
 
 
813
To set a POINTER type field to ``NULL``, you can assign ``None``::
 
814
 
 
815
   >>> bar.values = None
 
816
   >>>
 
817
 
 
818
.. XXX list other conversions...
 
819
 
 
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::
 
825
 
 
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
 
830
   >>>
 
831
 
 
832
For these cases, the ``cast`` function is handy.
 
833
 
 
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::
 
839
 
 
840
   >>> a = (c_byte * 4)()
 
841
   >>> cast(a, POINTER(c_int))
 
842
   <ctypes.LP_c_long object at ...>
 
843
   >>>
 
844
 
 
845
So, ``cast`` can be used to assign to the ``values`` field of ``Bar`` the
 
846
structure::
 
847
 
 
848
   >>> bar = Bar()
 
849
   >>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
 
850
   >>> print bar.values[0]
 
851
   0
 
852
   >>>
 
853
 
 
854
 
 
855
.. _ctypes-incomplete-types:
 
856
 
 
857
Incomplete Types
 
858
^^^^^^^^^^^^^^^^
 
859
 
 
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
 
862
later::
 
863
 
 
864
   struct cell; /* forward declaration */
 
865
 
 
866
   struct {
 
867
       char *name;
 
868
       struct cell *next;
 
869
   } cell;
 
870
 
 
871
The straightforward translation into ctypes code would be this, but it does not
 
872
work::
 
873
 
 
874
   >>> class cell(Structure):
 
875
   ...     _fields_ = [("name", c_char_p),
 
876
   ...                 ("next", POINTER(cell))]
 
877
   ...
 
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
 
882
   >>>
 
883
 
 
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::
 
887
 
 
888
   >>> from ctypes import *
 
889
   >>> class cell(Structure):
 
890
   ...     pass
 
891
   ...
 
892
   >>> cell._fields_ = [("name", c_char_p),
 
893
   ...                  ("next", POINTER(cell))]
 
894
   >>>
 
895
 
 
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::
 
898
 
 
899
   >>> c1 = cell()
 
900
   >>> c1.name = "foo"
 
901
   >>> c2 = cell()
 
902
   >>> c2.name = "bar"
 
903
   >>> c1.next = pointer(c2)
 
904
   >>> c2.next = pointer(c1)
 
905
   >>> p = c1
 
906
   >>> for i in range(8):
 
907
   ...     print p.name,
 
908
   ...     p = p.next[0]
 
909
   ...
 
910
   foo bar foo bar foo bar foo bar
 
911
   >>>
 
912
 
 
913
 
 
914
.. _ctypes-callback-functions:
 
915
 
 
916
Callback functions
 
917
^^^^^^^^^^^^^^^^^^
 
918
 
 
919
``ctypes`` allows to create C callable function pointers from Python callables.
 
920
These are sometimes called *callback functions*.
 
921
 
 
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.
 
925
 
 
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
 
929
convention.
 
930
 
 
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
 
933
arguments.
 
934
 
 
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::
 
938
 
 
939
   >>> IntArray5 = c_int * 5
 
940
   >>> ia = IntArray5(5, 1, 7, 33, 99)
 
941
   >>> qsort = libc.qsort
 
942
   >>> qsort.restype = None
 
943
   >>>
 
944
 
 
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.
 
950
 
 
951
So our callback function receives pointers to integers, and must return an
 
952
integer. First we create the ``type`` for the callback function::
 
953
 
 
954
   >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
 
955
   >>>
 
956
 
 
957
For the first implementation of the callback function, we simply print the
 
958
arguments we get, and return 0 (incremental development ;-)::
 
959
 
 
960
   >>> def py_cmp_func(a, b):
 
961
   ...     print "py_cmp_func", a, b
 
962
   ...     return 0
 
963
   ...
 
964
   >>>
 
965
 
 
966
Create the C callable callback::
 
967
 
 
968
   >>> cmp_func = CMPFUNC(py_cmp_func)
 
969
   >>>
 
970
 
 
971
And we're ready to go::
 
972
 
 
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...>
 
984
   >>>
 
985
 
 
986
We know how to access the contents of a pointer, so lets redefine our callback::
 
987
 
 
988
   >>> def py_cmp_func(a, b):
 
989
   ...     print "py_cmp_func", a[0], b[0]
 
990
   ...     return 0
 
991
   ...
 
992
   >>> cmp_func = CMPFUNC(py_cmp_func)
 
993
   >>>
 
994
 
 
995
Here is what we get on Windows::
 
996
 
 
997
   >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
 
998
   py_cmp_func 7 1
 
999
   py_cmp_func 33 1
 
1000
   py_cmp_func 99 1
 
1001
   py_cmp_func 5 1
 
1002
   py_cmp_func 7 5
 
1003
   py_cmp_func 33 5
 
1004
   py_cmp_func 99 5
 
1005
   py_cmp_func 7 99
 
1006
   py_cmp_func 33 99
 
1007
   py_cmp_func 7 33
 
1008
   >>>
 
1009
 
 
1010
It is funny to see that on linux the sort function seems to work much more
 
1011
efficient, it is doing less comparisons::
 
1012
 
 
1013
   >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX
 
1014
   py_cmp_func 5 1
 
1015
   py_cmp_func 33 99
 
1016
   py_cmp_func 7 33
 
1017
   py_cmp_func 5 7
 
1018
   py_cmp_func 1 7
 
1019
   >>>
 
1020
 
 
1021
Ah, we're nearly done! The last step is to actually compare the two items and
 
1022
return a useful result::
 
1023
 
 
1024
   >>> def py_cmp_func(a, b):
 
1025
   ...     print "py_cmp_func", a[0], b[0]
 
1026
   ...     return a[0] - b[0]
 
1027
   ...
 
1028
   >>>
 
1029
 
 
1030
Final run on Windows::
 
1031
 
 
1032
   >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +WINDOWS
 
1033
   py_cmp_func 33 7
 
1034
   py_cmp_func 99 33
 
1035
   py_cmp_func 5 99
 
1036
   py_cmp_func 1 99
 
1037
   py_cmp_func 33 7
 
1038
   py_cmp_func 1 33
 
1039
   py_cmp_func 5 33
 
1040
   py_cmp_func 5 7
 
1041
   py_cmp_func 1 7
 
1042
   py_cmp_func 5 1
 
1043
   >>>
 
1044
 
 
1045
and on Linux::
 
1046
 
 
1047
   >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX
 
1048
   py_cmp_func 5 1
 
1049
   py_cmp_func 33 99
 
1050
   py_cmp_func 7 33
 
1051
   py_cmp_func 1 7
 
1052
   py_cmp_func 5 7
 
1053
   >>>
 
1054
 
 
1055
It is quite interesting to see that the Windows :func:`qsort` function needs
 
1056
more comparisons than the linux version!
 
1057
 
 
1058
As we can easily check, our array is sorted now::
 
1059
 
 
1060
   >>> for i in ia: print i,
 
1061
   ...
 
1062
   1 5 7 33 99
 
1063
   >>>
 
1064
 
 
1065
**Important note for callback functions:**
 
1066
 
 
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.
 
1070
 
 
1071
 
 
1072
.. _ctypes-accessing-values-exported-from-dlls:
 
1073
 
 
1074
Accessing values exported from dlls
 
1075
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
1076
 
 
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
 
1080
startup.
 
1081
 
 
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
 
1084
api::
 
1085
 
 
1086
   >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
 
1087
   >>> print opt_flag
 
1088
   c_long(0)
 
1089
   >>>
 
1090
 
 
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
 
1093
specified.
 
1094
 
 
1095
An extended example which also demonstrates the use of pointers accesses the
 
1096
``PyImport_FrozenModules`` pointer exported by Python.
 
1097
 
 
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
 
1102
frozen modules.*
 
1103
 
 
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``::
 
1106
 
 
1107
   >>> from ctypes import *
 
1108
   >>>
 
1109
   >>> class struct_frozen(Structure):
 
1110
   ...     _fields_ = [("name", c_char_p),
 
1111
   ...                 ("code", POINTER(c_ubyte)),
 
1112
   ...                 ("size", c_int)]
 
1113
   ...
 
1114
   >>>
 
1115
 
 
1116
We have defined the ``struct _frozen`` data type, so we can get the pointer to
 
1117
the table::
 
1118
 
 
1119
   >>> FrozenTable = POINTER(struct_frozen)
 
1120
   >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
 
1121
   >>>
 
1122
 
 
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::
 
1128
 
 
1129
   >>> for item in table:
 
1130
   ...    print item.name, item.size
 
1131
   ...    if item.name is None:
 
1132
   ...        break
 
1133
   ...
 
1134
   __hello__ 104
 
1135
   __phello__ -104
 
1136
   __phello__.spam 104
 
1137
   None 0
 
1138
   >>>
 
1139
 
 
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.
 
1143
 
 
1144
 
 
1145
.. _ctypes-surprises:
 
1146
 
 
1147
Surprises
 
1148
^^^^^^^^^
 
1149
 
 
1150
There are some edges in ``ctypes`` where you may be expect something else than
 
1151
what actually happens.
 
1152
 
 
1153
Consider the following example::
 
1154
 
 
1155
   >>> from ctypes import *
 
1156
   >>> class POINT(Structure):
 
1157
   ...     _fields_ = ("x", c_int), ("y", c_int)
 
1158
   ...
 
1159
   >>> class RECT(Structure):
 
1160
   ...     _fields_ = ("a", POINT), ("b", POINT)
 
1161
   ...
 
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
 
1166
   1 2 3 4
 
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
 
1170
   3 4 3 4
 
1171
   >>>
 
1172
 
 
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::
 
1175
 
 
1176
   >>> temp0, temp1 = rc.b, rc.a
 
1177
   >>> rc.a = temp0
 
1178
   >>> rc.b = temp1
 
1179
   >>>
 
1180
 
 
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.
 
1186
 
 
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.
 
1190
 
 
1191
Another example that may behave different from what one would expect is this::
 
1192
 
 
1193
   >>> s = c_char_p()
 
1194
   >>> s.value = "abc def ghi"
 
1195
   >>> s.value
 
1196
   'abc def ghi'
 
1197
   >>> s.value is s.value
 
1198
   False
 
1199
   >>>
 
1200
 
 
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!
 
1206
 
 
1207
 
 
1208
.. _ctypes-variable-sized-data-types:
 
1209
 
 
1210
Variable-sized data types
 
1211
^^^^^^^^^^^^^^^^^^^^^^^^^
 
1212
 
 
1213
``ctypes`` provides some support for variable-sized arrays and structures (this
 
1214
was added in version 0.9.9.7).
 
1215
 
 
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::
 
1221
 
 
1222
   >>> short_array = (c_short * 4)()
 
1223
   >>> print sizeof(short_array)
 
1224
   8
 
1225
   >>> resize(short_array, 4)
 
1226
   Traceback (most recent call last):
 
1227
       ...
 
1228
   ValueError: minimum size is 8
 
1229
   >>> resize(short_array, 32)
 
1230
   >>> sizeof(short_array)
 
1231
   32
 
1232
   >>> sizeof(type(short_array))
 
1233
   8
 
1234
   >>>
 
1235
 
 
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::
 
1239
 
 
1240
   >>> short_array[:]
 
1241
   [0, 0, 0, 0]
 
1242
   >>> short_array[7]
 
1243
   Traceback (most recent call last):
 
1244
       ...
 
1245
   IndexError: invalid index
 
1246
   >>>
 
1247
 
 
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.
 
1251
 
 
1252
 
 
1253
.. _ctypes-ctypes-reference:
 
1254
 
 
1255
ctypes reference
 
1256
----------------
 
1257
 
 
1258
 
 
1259
.. _ctypes-finding-shared-libraries:
 
1260
 
 
1261
Finding shared libraries
 
1262
^^^^^^^^^^^^^^^^^^^^^^^^
 
1263
 
 
1264
When programming in a compiled language, shared libraries are accessed when
 
1265
compiling/linking a program, and when the program is run.
 
1266
 
 
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.
 
1271
 
 
1272
The ``ctypes.util`` module provides a function which can help to determine the
 
1273
library to load.
 
1274
 
 
1275
 
 
1276
.. data:: find_library(name)
 
1277
   :noindex:
 
1278
 
 
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``.
 
1283
 
 
1284
The exact functionality is system dependent.
 
1285
 
 
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::
 
1289
 
 
1290
   >>> from ctypes.util import find_library
 
1291
   >>> find_library("m")
 
1292
   'libm.so.6'
 
1293
   >>> find_library("c")
 
1294
   'libc.so.6'
 
1295
   >>> find_library("bz2")
 
1296
   'libbz2.so.1.0'
 
1297
   >>>
 
1298
 
 
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::
 
1301
 
 
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'
 
1311
   >>>
 
1312
 
 
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``.
 
1316
 
 
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.
 
1320
 
 
1321
 
 
1322
.. _ctypes-loading-shared-libraries:
 
1323
 
 
1324
Loading shared libraries
 
1325
^^^^^^^^^^^^^^^^^^^^^^^^
 
1326
 
 
1327
There are several ways to loaded shared libraries into the Python process.  One
 
1328
way is to instantiate one of the following classes:
 
1329
 
 
1330
 
 
1331
.. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
 
1332
 
 
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
 
1335
   ``int``.
 
1336
 
 
1337
 
 
1338
.. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
 
1339
 
 
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.
 
1346
 
 
1347
 
 
1348
.. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
 
1349
 
 
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.
 
1353
 
 
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
 
1356
   platform.
 
1357
 
 
1358
The Python :term:`global interpreter lock` is released before calling any
 
1359
function exported by these libraries, and reacquired afterwards.
 
1360
 
 
1361
 
 
1362
.. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)
 
1363
 
 
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.
 
1368
 
 
1369
   Thus, this is only useful to call Python C api functions directly.
 
1370
 
 
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
 
1376
it.
 
1377
 
 
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.
 
1380
 
 
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.
 
1388
 
 
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.
 
1392
 
 
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
 
1398
code.
 
1399
 
 
1400
.. versionadded:: 2.6
 
1401
   The ``use_last_error`` and ``use_errno`` optional parameters
 
1402
   were added.
 
1403
 
 
1404
.. data:: RTLD_GLOBAL
 
1405
   :noindex:
 
1406
 
 
1407
   Flag to use as *mode* parameter.  On platforms where this flag is not available,
 
1408
   it is defined as the integer zero.
 
1409
 
 
1410
 
 
1411
.. data:: RTLD_LOCAL
 
1412
   :noindex:
 
1413
 
 
1414
   Flag to use as *mode* parameter.  On platforms where this is not available, it
 
1415
   is the same as *RTLD_GLOBAL*.
 
1416
 
 
1417
 
 
1418
.. data:: DEFAULT_MODE
 
1419
   :noindex:
 
1420
 
 
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*.
 
1423
 
 
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.
 
1429
 
 
1430
The following public attributes are available, their name starts with an
 
1431
underscore to not clash with exported function names:
 
1432
 
 
1433
 
 
1434
.. attribute:: PyDLL._handle
 
1435
 
 
1436
   The system handle used to access the library.
 
1437
 
 
1438
 
 
1439
.. attribute:: PyDLL._name
 
1440
 
 
1441
   The name of the library passed in the constructor.
 
1442
 
 
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
 
1446
loader instance.
 
1447
 
 
1448
 
 
1449
.. class:: LibraryLoader(dlltype)
 
1450
 
 
1451
   Class which loads shared libraries.  ``dlltype`` should be one of the
 
1452
   :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types.
 
1453
 
 
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.
 
1457
 
 
1458
 
 
1459
   .. method:: LoadLibrary(name)
 
1460
 
 
1461
      Load a shared library into the process and return it.  This method always
 
1462
      returns a new instance of the library.
 
1463
 
 
1464
These prefabricated library loaders are available:
 
1465
 
 
1466
 
 
1467
.. data:: cdll
 
1468
   :noindex:
 
1469
 
 
1470
   Creates :class:`CDLL` instances.
 
1471
 
 
1472
 
 
1473
.. data:: windll
 
1474
   :noindex:
 
1475
 
 
1476
   Windows only: Creates :class:`WinDLL` instances.
 
1477
 
 
1478
 
 
1479
.. data:: oledll
 
1480
   :noindex:
 
1481
 
 
1482
   Windows only: Creates :class:`OleDLL` instances.
 
1483
 
 
1484
 
 
1485
.. data:: pydll
 
1486
   :noindex:
 
1487
 
 
1488
   Creates :class:`PyDLL` instances.
 
1489
 
 
1490
For accessing the C Python api directly, a ready-to-use Python shared library
 
1491
object is available:
 
1492
 
 
1493
 
 
1494
.. data:: pythonapi
 
1495
   :noindex:
 
1496
 
 
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.
 
1501
 
 
1502
 
 
1503
.. _ctypes-foreign-functions:
 
1504
 
 
1505
Foreign functions
 
1506
^^^^^^^^^^^^^^^^^
 
1507
 
 
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:
 
1513
 
 
1514
 
 
1515
.. class:: _FuncPtr
 
1516
 
 
1517
   Base class for C callable foreign functions.
 
1518
 
 
1519
   Instances of foreign functions are also C compatible data types; they
 
1520
   represent C function pointers.
 
1521
 
 
1522
   This behavior can be customized by assigning to special attributes of the
 
1523
   foreign function object.
 
1524
 
 
1525
 
 
1526
   .. attribute:: restype
 
1527
 
 
1528
      Assign a ctypes type to specify the result type of the foreign function.
 
1529
      Use ``None`` for ``void`` a function not returning anything.
 
1530
 
 
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.
 
1537
 
 
1538
 
 
1539
   .. attribute:: argtypes
 
1540
 
 
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.
 
1546
 
 
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.
 
1553
 
 
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.
 
1558
 
 
1559
 
 
1560
   .. attribute:: errcheck
 
1561
 
 
1562
      Assign a Python function or another callable to this attribute. The
 
1563
      callable will be called with three or more arguments:
 
1564
 
 
1565
      .. function:: callable(result, func, arguments)
 
1566
         :noindex:
 
1567
 
 
1568
         ``result`` is what the foreign function returns, as specified
 
1569
         by the :attr:`restype` attribute.
 
1570
 
 
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.
 
1574
 
 
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.
 
1578
 
 
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.
 
1582
 
 
1583
 
 
1584
.. exception:: ArgumentError()
 
1585
 
 
1586
   This exception is raised when a foreign function call cannot convert one of the
 
1587
   passed arguments.
 
1588
 
 
1589
 
 
1590
.. _ctypes-function-prototypes:
 
1591
 
 
1592
Function prototypes
 
1593
^^^^^^^^^^^^^^^^^^^
 
1594
 
 
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.
 
1600
 
 
1601
 
 
1602
.. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
 
1603
 
 
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.
 
1609
 
 
1610
   .. versionchanged:: 2.6
 
1611
      The optional `use_errno` and `use_last_error` parameters were
 
1612
      added.
 
1613
 
 
1614
 
 
1615
.. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
 
1616
 
 
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.
 
1621
 
 
1622
 
 
1623
.. function:: PYFUNCTYPE(restype, *argtypes)
 
1624
 
 
1625
   The returned function prototype creates functions that use the Python calling
 
1626
   convention.  The function will *not* release the GIL during the call.
 
1627
 
 
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:
 
1630
 
 
1631
 
 
1632
   .. function:: prototype(address)
 
1633
      :noindex:
 
1634
      :module:
 
1635
 
 
1636
      Returns a foreign function at the specified address which must be an integer.
 
1637
 
 
1638
 
 
1639
   .. function:: prototype(callable)
 
1640
      :noindex:
 
1641
      :module:
 
1642
 
 
1643
      Create a C callable function (a callback function) from a Python ``callable``.
 
1644
 
 
1645
 
 
1646
   .. function:: prototype(func_spec[, paramflags])
 
1647
      :noindex:
 
1648
      :module:
 
1649
 
 
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.
 
1654
 
 
1655
 
 
1656
   .. function:: prototype(vtbl_index, name[, paramflags[, iid]])
 
1657
      :noindex:
 
1658
      :module:
 
1659
 
 
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.
 
1664
 
 
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.
 
1668
 
 
1669
   The optional *paramflags* parameter creates foreign function wrappers with much
 
1670
   more functionality than the features described above.
 
1671
 
 
1672
   *paramflags* must be a tuple of the same length as :attr:`argtypes`.
 
1673
 
 
1674
   Each item in this tuple contains further information about a parameter, it must
 
1675
   be a tuple containing one, two, or three items.
 
1676
 
 
1677
   The first item is an integer containing a combination of direction
 
1678
   flags for the parameter:
 
1679
 
 
1680
      1
 
1681
         Specifies an input parameter to the function.
 
1682
 
 
1683
      2
 
1684
         Output parameter.  The foreign function fills in a value.
 
1685
 
 
1686
      4
 
1687
         Input parameter which defaults to the integer zero.
 
1688
 
 
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.
 
1691
 
 
1692
   The optional third item is the default value for this parameter.
 
1693
 
 
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::
 
1697
 
 
1698
   WINUSERAPI int WINAPI
 
1699
   MessageBoxA(
 
1700
       HWND hWnd ,
 
1701
       LPCSTR lpText,
 
1702
       LPCSTR lpCaption,
 
1703
       UINT uType);
 
1704
 
 
1705
Here is the wrapping with ``ctypes``::
 
1706
 
 
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)
 
1712
   >>>
 
1713
 
 
1714
The MessageBox foreign function can now be called in these ways::
 
1715
 
 
1716
   >>> MessageBox()
 
1717
   >>> MessageBox(text="Spam, spam, spam")
 
1718
   >>> MessageBox(flags=2, text="foo bar")
 
1719
   >>>
 
1720
 
 
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::
 
1724
 
 
1725
   WINUSERAPI BOOL WINAPI
 
1726
   GetWindowRect(
 
1727
        HWND hWnd,
 
1728
        LPRECT lpRect);
 
1729
 
 
1730
Here is the wrapping with ``ctypes``::
 
1731
 
 
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)
 
1737
   >>>
 
1738
 
 
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.
 
1743
 
 
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::
 
1748
 
 
1749
   >>> def errcheck(result, func, args):
 
1750
   ...     if not result:
 
1751
   ...         raise WinError()
 
1752
   ...     return args
 
1753
   ...
 
1754
   >>> GetWindowRect.errcheck = errcheck
 
1755
   >>>
 
1756
 
 
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::
 
1762
 
 
1763
   >>> def errcheck(result, func, args):
 
1764
   ...     if not result:
 
1765
   ...         raise WinError()
 
1766
   ...     rc = args[1]
 
1767
   ...     return rc.left, rc.top, rc.bottom, rc.right
 
1768
   ...
 
1769
   >>> GetWindowRect.errcheck = errcheck
 
1770
   >>>
 
1771
 
 
1772
 
 
1773
.. _ctypes-utility-functions:
 
1774
 
 
1775
Utility functions
 
1776
^^^^^^^^^^^^^^^^^
 
1777
 
 
1778
 
 
1779
.. function:: addressof(obj)
 
1780
 
 
1781
   Returns the address of the memory buffer as integer.  ``obj`` must be an
 
1782
   instance of a ctypes type.
 
1783
 
 
1784
 
 
1785
.. function:: alignment(obj_or_type)
 
1786
 
 
1787
   Returns the alignment requirements of a ctypes type. ``obj_or_type`` must be a
 
1788
   ctypes type or instance.
 
1789
 
 
1790
 
 
1791
.. function:: byref(obj[, offset])
 
1792
 
 
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.
 
1796
 
 
1797
   ``byref(obj, offset)`` corresponds to this C code::
 
1798
 
 
1799
      (((char *)&obj) + offset)
 
1800
 
 
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.
 
1804
 
 
1805
   .. versionadded:: 2.6
 
1806
      The ``offset`` optional argument was added.
 
1807
 
 
1808
.. function:: cast(obj, type)
 
1809
 
 
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
 
1813
   pointer.
 
1814
 
 
1815
 
 
1816
.. function:: create_string_buffer(init_or_size[, size])
 
1817
 
 
1818
   This function creates a mutable character buffer. The returned object is a
 
1819
   ctypes array of :class:`c_char`.
 
1820
 
 
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.
 
1823
 
 
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.
 
1828
 
 
1829
   If the first parameter is a unicode string, it is converted into an 8-bit string
 
1830
   according to ctypes conversion rules.
 
1831
 
 
1832
 
 
1833
.. function:: create_unicode_buffer(init_or_size[, size])
 
1834
 
 
1835
   This function creates a mutable unicode character buffer. The returned object is
 
1836
   a ctypes array of :class:`c_wchar`.
 
1837
 
 
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.
 
1840
 
 
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
 
1845
   be used.
 
1846
 
 
1847
   If the first parameter is a 8-bit string, it is converted into an unicode string
 
1848
   according to ctypes conversion rules.
 
1849
 
 
1850
 
 
1851
.. function:: DllCanUnloadNow()
 
1852
 
 
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.
 
1856
 
 
1857
 
 
1858
.. function:: DllGetClassObject()
 
1859
 
 
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.
 
1863
 
 
1864
.. function:: find_library(name)
 
1865
   :module: ctypes.util
 
1866
 
 
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``.
 
1871
 
 
1872
   The exact functionality is system dependent.
 
1873
 
 
1874
   .. versionchanged:: 2.6
 
1875
      Windows only: ``find_library("m")`` or
 
1876
      ``find_library("c")`` return the result of a call to
 
1877
      ``find_msvcrt()``.
 
1878
 
 
1879
.. function:: find_msvcrt()
 
1880
   :module: ctypes.util
 
1881
 
 
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.
 
1885
 
 
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.
 
1889
 
 
1890
   .. versionadded:: 2.6
 
1891
 
 
1892
.. function:: FormatError([code])
 
1893
 
 
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
 
1896
   GetLastError.
 
1897
 
 
1898
 
 
1899
.. function:: GetLastError()
 
1900
 
 
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.
 
1904
 
 
1905
.. function:: get_errno()
 
1906
 
 
1907
   Returns the current value of the ctypes-private copy of the system
 
1908
   `errno` variable in the calling thread.
 
1909
 
 
1910
   .. versionadded:: 2.6
 
1911
 
 
1912
.. function:: get_last_error()
 
1913
 
 
1914
   Windows only: returns the current value of the ctypes-private copy of the system
 
1915
   `LastError` variable in the calling thread.
 
1916
 
 
1917
   .. versionadded:: 2.6
 
1918
 
 
1919
.. function:: memmove(dst, src, count)
 
1920
 
 
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.
 
1924
 
 
1925
 
 
1926
.. function:: memset(dst, c, count)
 
1927
 
 
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.
 
1931
 
 
1932
 
 
1933
.. function:: POINTER(type)
 
1934
 
 
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.
 
1938
 
 
1939
 
 
1940
.. function:: pointer(obj)
 
1941
 
 
1942
   This function creates a new pointer instance, pointing to ``obj``. The returned
 
1943
   object is of the type POINTER(type(obj)).
 
1944
 
 
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.
 
1947
 
 
1948
 
 
1949
.. function:: resize(obj, size)
 
1950
 
 
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.
 
1955
 
 
1956
 
 
1957
.. function:: set_conversion_mode(encoding, errors)
 
1958
 
 
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"``.
 
1964
 
 
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')``.
 
1968
 
 
1969
 
 
1970
.. function:: set_errno(value)
 
1971
 
 
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
 
1974
   previous value.
 
1975
 
 
1976
   .. versionadded:: 2.6
 
1977
 
 
1978
.. function:: set_last_error(value)
 
1979
 
 
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.
 
1983
 
 
1984
   .. versionadded:: 2.6
 
1985
 
 
1986
.. function:: sizeof(obj_or_type)
 
1987
 
 
1988
   Returns the size in bytes of a ctypes type or instance memory buffer. Does the
 
1989
   same as the C ``sizeof()`` function.
 
1990
 
 
1991
 
 
1992
.. function:: string_at(address[, size])
 
1993
 
 
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
 
1996
   zero-terminated.
 
1997
 
 
1998
 
 
1999
.. function:: WinError(code=None, descr=None)
 
2000
 
 
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
 
2005
   error.
 
2006
 
 
2007
 
 
2008
.. function:: wstring_at(address)
 
2009
 
 
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
 
2013
   zero-terminated.
 
2014
 
 
2015
 
 
2016
.. _ctypes-data-types:
 
2017
 
 
2018
Data types
 
2019
^^^^^^^^^^
 
2020
 
 
2021
 
 
2022
.. class:: _CData
 
2023
 
 
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.
 
2030
 
 
2031
   Common methods of ctypes data types, these are all class methods (to be
 
2032
   exact, they are methods of the :term:`metaclass`):
 
2033
 
 
2034
 
 
2035
   .. method:: _CData.from_buffer(source[, offset])
 
2036
 
 
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
 
2042
      is raised.
 
2043
 
 
2044
      .. versionadded:: 2.6
 
2045
 
 
2046
   .. method:: _CData.from_buffer_copy(source[, offset])
 
2047
 
 
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.
 
2053
 
 
2054
      .. versionadded:: 2.6
 
2055
 
 
2056
 
 
2057
   .. method:: from_address(address)
 
2058
 
 
2059
      This method returns a ctypes type instance using the memory specified by
 
2060
      address which must be an integer.
 
2061
 
 
2062
 
 
2063
   .. method:: from_param(obj)
 
2064
 
 
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.
 
2069
 
 
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.
 
2073
 
 
2074
 
 
2075
   .. method:: in_dll(library, name)
 
2076
 
 
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.
 
2080
 
 
2081
 
 
2082
   Common instance variables of ctypes data types:
 
2083
 
 
2084
 
 
2085
   .. attribute:: _b_base_
 
2086
 
 
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
 
2090
      memory block.
 
2091
 
 
2092
 
 
2093
   .. attribute:: _b_needsfree_
 
2094
 
 
2095
      This read-only variable is true when the ctypes data instance has
 
2096
      allocated the memory block itself, false otherwise.
 
2097
 
 
2098
 
 
2099
   .. attribute:: _objects
 
2100
 
 
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.
 
2105
 
 
2106
 
 
2107
.. _ctypes-fundamental-data-types-2:
 
2108
 
 
2109
Fundamental data types
 
2110
^^^^^^^^^^^^^^^^^^^^^^
 
2111
 
 
2112
 
 
2113
.. class:: _SimpleCData
 
2114
 
 
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.
 
2119
 
 
2120
   .. versionchanged:: 2.6
 
2121
      ctypes data types that are not and do not contain pointers can
 
2122
      now be pickled.
 
2123
 
 
2124
   Instances have a single attribute:
 
2125
 
 
2126
 
 
2127
   .. attribute:: value
 
2128
 
 
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
 
2132
      unicode string.
 
2133
 
 
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.
 
2138
 
 
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.
 
2144
 
 
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.
 
2149
 
 
2150
These are the fundamental ctypes data types:
 
2151
 
 
2152
 
 
2153
.. class:: c_byte
 
2154
 
 
2155
   Represents the C signed char datatype, and interprets the value as small
 
2156
   integer. The constructor accepts an optional integer initializer; no overflow
 
2157
   checking is done.
 
2158
 
 
2159
 
 
2160
.. class:: c_char
 
2161
 
 
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.
 
2165
 
 
2166
 
 
2167
.. class:: c_char_p
 
2168
 
 
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.
 
2171
 
 
2172
 
 
2173
.. class:: c_double
 
2174
 
 
2175
   Represents the C double datatype. The constructor accepts an optional float
 
2176
   initializer.
 
2177
 
 
2178
 
 
2179
.. class:: c_longdouble
 
2180
 
 
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`.
 
2184
 
 
2185
   .. versionadded:: 2.6
 
2186
 
 
2187
.. class:: c_float
 
2188
 
 
2189
   Represents the C float datatype. The constructor accepts an optional float
 
2190
   initializer.
 
2191
 
 
2192
 
 
2193
.. class:: c_int
 
2194
 
 
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`.
 
2198
 
 
2199
 
 
2200
.. class:: c_int8
 
2201
 
 
2202
   Represents the C 8-bit ``signed int`` datatype. Usually an alias for
 
2203
   :class:`c_byte`.
 
2204
 
 
2205
 
 
2206
.. class:: c_int16
 
2207
 
 
2208
   Represents the C 16-bit signed int datatype. Usually an alias for
 
2209
   :class:`c_short`.
 
2210
 
 
2211
 
 
2212
.. class:: c_int32
 
2213
 
 
2214
   Represents the C 32-bit signed int datatype. Usually an alias for
 
2215
   :class:`c_int`.
 
2216
 
 
2217
 
 
2218
.. class:: c_int64
 
2219
 
 
2220
   Represents the C 64-bit ``signed int`` datatype. Usually an alias for
 
2221
   :class:`c_longlong`.
 
2222
 
 
2223
 
 
2224
.. class:: c_long
 
2225
 
 
2226
   Represents the C ``signed long`` datatype. The constructor accepts an optional
 
2227
   integer initializer; no overflow checking is done.
 
2228
 
 
2229
 
 
2230
.. class:: c_longlong
 
2231
 
 
2232
   Represents the C ``signed long long`` datatype. The constructor accepts an
 
2233
   optional integer initializer; no overflow checking is done.
 
2234
 
 
2235
 
 
2236
.. class:: c_short
 
2237
 
 
2238
   Represents the C ``signed short`` datatype. The constructor accepts an optional
 
2239
   integer initializer; no overflow checking is done.
 
2240
 
 
2241
 
 
2242
.. class:: c_size_t
 
2243
 
 
2244
   Represents the C ``size_t`` datatype.
 
2245
 
 
2246
 
 
2247
.. class:: c_ubyte
 
2248
 
 
2249
   Represents the C ``unsigned char`` datatype, it interprets the value as small
 
2250
   integer. The constructor accepts an optional integer initializer; no overflow
 
2251
   checking is done.
 
2252
 
 
2253
 
 
2254
.. class:: c_uint
 
2255
 
 
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`.
 
2259
 
 
2260
 
 
2261
.. class:: c_uint8
 
2262
 
 
2263
   Represents the C 8-bit unsigned int datatype. Usually an alias for
 
2264
   :class:`c_ubyte`.
 
2265
 
 
2266
 
 
2267
.. class:: c_uint16
 
2268
 
 
2269
   Represents the C 16-bit unsigned int datatype. Usually an alias for
 
2270
   :class:`c_ushort`.
 
2271
 
 
2272
 
 
2273
.. class:: c_uint32
 
2274
 
 
2275
   Represents the C 32-bit unsigned int datatype. Usually an alias for
 
2276
   :class:`c_uint`.
 
2277
 
 
2278
 
 
2279
.. class:: c_uint64
 
2280
 
 
2281
   Represents the C 64-bit unsigned int datatype. Usually an alias for
 
2282
   :class:`c_ulonglong`.
 
2283
 
 
2284
 
 
2285
.. class:: c_ulong
 
2286
 
 
2287
   Represents the C ``unsigned long`` datatype. The constructor accepts an optional
 
2288
   integer initializer; no overflow checking is done.
 
2289
 
 
2290
 
 
2291
.. class:: c_ulonglong
 
2292
 
 
2293
   Represents the C ``unsigned long long`` datatype. The constructor accepts an
 
2294
   optional integer initializer; no overflow checking is done.
 
2295
 
 
2296
 
 
2297
.. class:: c_ushort
 
2298
 
 
2299
   Represents the C ``unsigned short`` datatype. The constructor accepts an
 
2300
   optional integer initializer; no overflow checking is done.
 
2301
 
 
2302
 
 
2303
.. class:: c_void_p
 
2304
 
 
2305
   Represents the C ``void *`` type. The value is represented as integer. The
 
2306
   constructor accepts an optional integer initializer.
 
2307
 
 
2308
 
 
2309
.. class:: c_wchar
 
2310
 
 
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.
 
2314
 
 
2315
 
 
2316
.. class:: c_wchar_p
 
2317
 
 
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.
 
2321
 
 
2322
 
 
2323
.. class:: c_bool
 
2324
 
 
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
 
2327
   value.
 
2328
 
 
2329
   .. versionadded:: 2.6
 
2330
 
 
2331
 
 
2332
.. class:: HRESULT
 
2333
 
 
2334
   Windows only: Represents a :class:`HRESULT` value, which contains success or
 
2335
   error information for a function or method call.
 
2336
 
 
2337
 
 
2338
.. class:: py_object
 
2339
 
 
2340
   Represents the C ``PyObject *`` datatype.  Calling this without an argument
 
2341
   creates a ``NULL`` ``PyObject *`` pointer.
 
2342
 
 
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.
 
2346
 
 
2347
 
 
2348
.. _ctypes-structured-data-types:
 
2349
 
 
2350
Structured data types
 
2351
^^^^^^^^^^^^^^^^^^^^^
 
2352
 
 
2353
 
 
2354
.. class:: Union(*args, **kw)
 
2355
 
 
2356
   Abstract base class for unions in native byte order.
 
2357
 
 
2358
 
 
2359
.. class:: BigEndianStructure(*args, **kw)
 
2360
 
 
2361
   Abstract base class for structures in *big endian* byte order.
 
2362
 
 
2363
 
 
2364
.. class:: LittleEndianStructure(*args, **kw)
 
2365
 
 
2366
   Abstract base class for structures in *little endian* byte order.
 
2367
 
 
2368
Structures with non-native byte order cannot contain pointer type fields, or any
 
2369
other data types containing pointer type fields.
 
2370
 
 
2371
 
 
2372
.. class:: Structure(*args, **kw)
 
2373
 
 
2374
   Abstract base class for structures in *native* byte order.
 
2375
 
 
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
 
2380
 
 
2381
 
 
2382
   .. attribute:: _fields_
 
2383
 
 
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.
 
2387
 
 
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
 
2390
      field.
 
2391
 
 
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.
 
2394
 
 
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::
 
2398
 
 
2399
         class List(Structure):
 
2400
             pass
 
2401
         List._fields_ = [("pnext", POINTER(List)),
 
2402
                          ...
 
2403
                         ]
 
2404
 
 
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.
 
2409
 
 
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.
 
2414
 
 
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.
 
2418
 
 
2419
 
 
2420
   .. attribute:: _pack_
 
2421
 
 
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.
 
2425
 
 
2426
 
 
2427
   .. attribute:: _anonymous_
 
2428
 
 
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.
 
2432
 
 
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.
 
2437
 
 
2438
      Here is an example type (Windows)::
 
2439
 
 
2440
         class _U(Union):
 
2441
             _fields_ = [("lptdesc", POINTER(TYPEDESC)),
 
2442
                         ("lpadesc", POINTER(ARRAYDESC)),
 
2443
                         ("hreftype", HREFTYPE)]
 
2444
 
 
2445
         class TYPEDESC(Structure):
 
2446
             _fields_ = [("u", _U),
 
2447
                         ("vt", VARTYPE)]
 
2448
 
 
2449
             _anonymous_ = ("u",)
 
2450
 
 
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::
 
2457
 
 
2458
         td = TYPEDESC()
 
2459
         td.vt = VT_PTR
 
2460
         td.lptdesc = POINTER(some_type)
 
2461
         td.u.lptdesc = POINTER(some_type)
 
2462
 
 
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
 
2466
class.
 
2467
 
 
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
 
2473
:attr:`_fields_`.
 
2474
 
 
2475
 
 
2476
.. _ctypes-arrays-pointers:
 
2477
 
 
2478
Arrays and pointers
 
2479
^^^^^^^^^^^^^^^^^^^
 
2480
 
 
2481
Not yet written - please see the sections :ref:`ctypes-pointers` and
 
2482
section :ref:`ctypes-arrays` in the tutorial.
 
2483