blob: e389a633315ee819e57a3d743541830652e6590e [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
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
Georg Brandl116aa622007-08-15 14:28:22 +000010``ctypes`` is a foreign function library for Python. It provides C compatible
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000011data types, and allows calling functions in DLLs or shared libraries. It can be
Georg Brandl116aa622007-08-15 14:28:22 +000012used to wrap these libraries in pure Python.
13
14
15.. _ctypes-ctypes-tutorial:
16
17ctypes tutorial
18---------------
19
20Note: The code samples in this tutorial use ``doctest`` to make sure that they
21actually work. Since some code samples behave differently under Linux, Windows,
22or Mac OS X, they contain doctest directives in comments.
23
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000024Note: Some code samples reference the ctypes :class:`c_int` type. This type is
25an alias for the :class:`c_long` type on 32-bit systems. So, you should not be
Georg Brandl116aa622007-08-15 14:28:22 +000026confused if :class:`c_long` is printed if you would expect :class:`c_int` ---
27they are actually the same type.
28
29
30.. _ctypes-loading-dynamic-link-libraries:
31
32Loading dynamic link libraries
33^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
34
Benjamin Peterson3e4f0552008-09-02 00:31:15 +000035``ctypes`` exports the *cdll*, and on Windows *windll* and *oledll*
36objects, for loading dynamic link libraries.
Georg Brandl116aa622007-08-15 14:28:22 +000037
38You load libraries by accessing them as attributes of these objects. *cdll*
39loads libraries which export functions using the standard ``cdecl`` calling
40convention, while *windll* libraries call functions using the ``stdcall``
41calling convention. *oledll* also uses the ``stdcall`` calling convention, and
42assumes the functions return a Windows :class:`HRESULT` error code. The error
Thomas Heller2fadaa22008-06-16 19:56:33 +000043code is used to automatically raise a :class:`WindowsError` exception when
Georg Brandl116aa622007-08-15 14:28:22 +000044the function call fails.
45
46Here are some examples for Windows. Note that ``msvcrt`` is the MS standard C
47library containing most standard C functions, and uses the cdecl calling
48convention::
49
50 >>> from ctypes import *
Georg Brandl6911e3c2007-09-04 07:15:32 +000051 >>> print(windll.kernel32) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +000052 <WinDLL 'kernel32', handle ... at ...>
Georg Brandl6911e3c2007-09-04 07:15:32 +000053 >>> print(cdll.msvcrt) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +000054 <CDLL 'msvcrt', handle ... at ...>
55 >>> libc = cdll.msvcrt # doctest: +WINDOWS
56 >>>
57
Thomas Heller2fadaa22008-06-16 19:56:33 +000058Windows appends the usual ``.dll`` file suffix automatically.
Georg Brandl116aa622007-08-15 14:28:22 +000059
60On Linux, it is required to specify the filename *including* the extension to
Thomas Heller2fadaa22008-06-16 19:56:33 +000061load a library, so attribute access can not be used to load libraries. Either the
Georg Brandl116aa622007-08-15 14:28:22 +000062:meth:`LoadLibrary` method of the dll loaders should be used, or you should load
63the library by creating an instance of CDLL by calling the constructor::
64
65 >>> cdll.LoadLibrary("libc.so.6") # doctest: +LINUX
66 <CDLL 'libc.so.6', handle ... at ...>
67 >>> libc = CDLL("libc.so.6") # doctest: +LINUX
68 >>> libc # doctest: +LINUX
69 <CDLL 'libc.so.6', handle ... at ...>
70 >>>
71
Christian Heimes5b5e81c2007-12-31 16:14:33 +000072.. XXX Add section for Mac OS X.
Georg Brandl116aa622007-08-15 14:28:22 +000073
74
75.. _ctypes-accessing-functions-from-loaded-dlls:
76
77Accessing functions from loaded dlls
78^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
79
80Functions are accessed as attributes of dll objects::
81
82 >>> from ctypes import *
83 >>> libc.printf
84 <_FuncPtr object at 0x...>
Georg Brandl6911e3c2007-09-04 07:15:32 +000085 >>> print(windll.kernel32.GetModuleHandleA) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +000086 <_FuncPtr object at 0x...>
Georg Brandl6911e3c2007-09-04 07:15:32 +000087 >>> print(windll.kernel32.MyOwnFunction) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +000088 Traceback (most recent call last):
89 File "<stdin>", line 1, in ?
90 File "ctypes.py", line 239, in __getattr__
91 func = _StdcallFuncPtr(name, self)
92 AttributeError: function 'MyOwnFunction' not found
93 >>>
94
95Note that win32 system dlls like ``kernel32`` and ``user32`` often export ANSI
96as well as UNICODE versions of a function. The UNICODE version is exported with
97an ``W`` appended to the name, while the ANSI version is exported with an ``A``
98appended to the name. The win32 ``GetModuleHandle`` function, which returns a
99*module handle* for a given module name, has the following C prototype, and a
100macro is used to expose one of them as ``GetModuleHandle`` depending on whether
101UNICODE is defined or not::
102
103 /* ANSI version */
104 HMODULE GetModuleHandleA(LPCSTR lpModuleName);
105 /* UNICODE version */
106 HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
107
108*windll* does not try to select one of them by magic, you must access the
109version you need by specifying ``GetModuleHandleA`` or ``GetModuleHandleW``
Thomas Heller2fadaa22008-06-16 19:56:33 +0000110explicitly, and then call it with strings or unicode strings
Georg Brandl116aa622007-08-15 14:28:22 +0000111respectively.
112
113Sometimes, dlls export functions with names which aren't valid Python
114identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use ``getattr``
115to retrieve the function::
116
117 >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") # doctest: +WINDOWS
118 <_FuncPtr object at 0x...>
119 >>>
120
121On Windows, some dlls export functions not by name but by ordinal. These
122functions can be accessed by indexing the dll object with the ordinal number::
123
124 >>> cdll.kernel32[1] # doctest: +WINDOWS
125 <_FuncPtr object at 0x...>
126 >>> cdll.kernel32[0] # doctest: +WINDOWS
127 Traceback (most recent call last):
128 File "<stdin>", line 1, in ?
129 File "ctypes.py", line 310, in __getitem__
130 func = _StdcallFuncPtr(name, self)
131 AttributeError: function ordinal 0 not found
132 >>>
133
134
135.. _ctypes-calling-functions:
136
137Calling functions
138^^^^^^^^^^^^^^^^^
139
140You can call these functions like any other Python callable. This example uses
141the ``time()`` function, which returns system time in seconds since the Unix
142epoch, and the ``GetModuleHandleA()`` function, which returns a win32 module
143handle.
144
145This example calls both functions with a NULL pointer (``None`` should be used
146as the NULL pointer)::
147
Georg Brandl6911e3c2007-09-04 07:15:32 +0000148 >>> print(libc.time(None)) # doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000149 1150640792
Georg Brandl6911e3c2007-09-04 07:15:32 +0000150 >>> print(hex(windll.kernel32.GetModuleHandleA(None))) # doctest: +WINDOWS
Georg Brandl116aa622007-08-15 14:28:22 +0000151 0x1d000000
152 >>>
153
154``ctypes`` tries to protect you from calling functions with the wrong number of
155arguments or the wrong calling convention. Unfortunately this only works on
156Windows. It does this by examining the stack after the function returns, so
157although an error is raised the function *has* been called::
158
159 >>> windll.kernel32.GetModuleHandleA() # doctest: +WINDOWS
160 Traceback (most recent call last):
161 File "<stdin>", line 1, in ?
162 ValueError: Procedure probably called with not enough arguments (4 bytes missing)
163 >>> windll.kernel32.GetModuleHandleA(0, 0) # doctest: +WINDOWS
164 Traceback (most recent call last):
165 File "<stdin>", line 1, in ?
166 ValueError: Procedure probably called with too many arguments (4 bytes in excess)
167 >>>
168
169The same exception is raised when you call an ``stdcall`` function with the
170``cdecl`` calling convention, or vice versa::
171
172 >>> cdll.kernel32.GetModuleHandleA(None) # doctest: +WINDOWS
173 Traceback (most recent call last):
174 File "<stdin>", line 1, in ?
175 ValueError: Procedure probably called with not enough arguments (4 bytes missing)
176 >>>
177
178 >>> windll.msvcrt.printf("spam") # doctest: +WINDOWS
179 Traceback (most recent call last):
180 File "<stdin>", line 1, in ?
181 ValueError: Procedure probably called with too many arguments (4 bytes in excess)
182 >>>
183
184To find out the correct calling convention you have to look into the C header
185file or the documentation for the function you want to call.
186
187On Windows, ``ctypes`` uses win32 structured exception handling to prevent
188crashes from general protection faults when functions are called with invalid
189argument values::
190
191 >>> windll.kernel32.GetModuleHandleA(32) # doctest: +WINDOWS
192 Traceback (most recent call last):
193 File "<stdin>", line 1, in ?
194 WindowsError: exception: access violation reading 0x00000020
195 >>>
196
197There are, however, enough ways to crash Python with ``ctypes``, so you should
198be careful anyway.
199
Georg Brandl5c106642007-11-29 17:41:05 +0000200``None``, integers, byte strings and unicode strings are the only native
Georg Brandl116aa622007-08-15 14:28:22 +0000201Python objects that can directly be used as parameters in these function calls.
202``None`` is passed as a C ``NULL`` pointer, byte strings and unicode strings are
203passed as pointer to the memory block that contains their data (``char *`` or
Georg Brandl5c106642007-11-29 17:41:05 +0000204``wchar_t *``). Python integers are passed as the platforms
Georg Brandl116aa622007-08-15 14:28:22 +0000205default C ``int`` type, their value is masked to fit into the C type.
206
207Before we move on calling functions with other parameter types, we have to learn
208more about ``ctypes`` data types.
209
210
211.. _ctypes-fundamental-data-types:
212
213Fundamental data types
214^^^^^^^^^^^^^^^^^^^^^^
215
216``ctypes`` defines a number of primitive C compatible data types :
217
218 +----------------------+--------------------------------+----------------------------+
219 | ctypes type | C type | Python type |
220 +======================+================================+============================+
221 | :class:`c_char` | ``char`` | 1-character string |
222 +----------------------+--------------------------------+----------------------------+
223 | :class:`c_wchar` | ``wchar_t`` | 1-character unicode string |
224 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000225 | :class:`c_byte` | ``char`` | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000226 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000227 | :class:`c_ubyte` | ``unsigned char`` | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000228 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000229 | :class:`c_short` | ``short`` | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000230 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000231 | :class:`c_ushort` | ``unsigned short`` | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000232 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000233 | :class:`c_int` | ``int`` | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000234 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000235 | :class:`c_uint` | ``unsigned int`` | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000236 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000237 | :class:`c_long` | ``long`` | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000238 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000239 | :class:`c_ulong` | ``unsigned long`` | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000240 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000241 | :class:`c_longlong` | ``__int64`` or ``long long`` | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000242 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000243 | :class:`c_ulonglong` | ``unsigned __int64`` or | int |
Georg Brandl116aa622007-08-15 14:28:22 +0000244 | | ``unsigned long long`` | |
245 +----------------------+--------------------------------+----------------------------+
246 | :class:`c_float` | ``float`` | float |
247 +----------------------+--------------------------------+----------------------------+
248 | :class:`c_double` | ``double`` | float |
249 +----------------------+--------------------------------+----------------------------+
Thomas Wouters89d996e2007-09-08 17:39:28 +0000250 | :class:`c_longdouble`| ``long double`` | float |
251 +----------------------+--------------------------------+----------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000252 | :class:`c_char_p` | ``char *`` (NUL terminated) | string or ``None`` |
253 +----------------------+--------------------------------+----------------------------+
254 | :class:`c_wchar_p` | ``wchar_t *`` (NUL terminated) | unicode or ``None`` |
255 +----------------------+--------------------------------+----------------------------+
Georg Brandl5c106642007-11-29 17:41:05 +0000256 | :class:`c_void_p` | ``void *`` | int or ``None`` |
Georg Brandl116aa622007-08-15 14:28:22 +0000257 +----------------------+--------------------------------+----------------------------+
258
259
260All these types can be created by calling them with an optional initializer of
261the correct type and value::
262
263 >>> c_int()
264 c_long(0)
265 >>> c_char_p("Hello, World")
266 c_char_p('Hello, World')
267 >>> c_ushort(-3)
268 c_ushort(65533)
269 >>>
270
271Since these types are mutable, their value can also be changed afterwards::
272
273 >>> i = c_int(42)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000274 >>> print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000275 c_long(42)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000276 >>> print(i.value)
Georg Brandl116aa622007-08-15 14:28:22 +0000277 42
278 >>> i.value = -99
Georg Brandl6911e3c2007-09-04 07:15:32 +0000279 >>> print(i.value)
Georg Brandl116aa622007-08-15 14:28:22 +0000280 -99
281 >>>
282
283Assigning a new value to instances of the pointer types :class:`c_char_p`,
284:class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they
285point to, *not the contents* of the memory block (of course not, because Python
286strings are immutable)::
287
288 >>> s = "Hello, World"
289 >>> c_s = c_char_p(s)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000290 >>> print(c_s)
Georg Brandl116aa622007-08-15 14:28:22 +0000291 c_char_p('Hello, World')
292 >>> c_s.value = "Hi, there"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000293 >>> print(c_s)
Georg Brandl116aa622007-08-15 14:28:22 +0000294 c_char_p('Hi, there')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000295 >>> print(s) # first string is unchanged
Georg Brandl116aa622007-08-15 14:28:22 +0000296 Hello, World
297 >>>
298
299You should be careful, however, not to pass them to functions expecting pointers
300to mutable memory. If you need mutable memory blocks, ctypes has a
301``create_string_buffer`` function which creates these in various ways. The
302current memory block contents can be accessed (or changed) with the ``raw``
303property; if you want to access it as NUL terminated string, use the ``value``
304property::
305
306 >>> from ctypes import *
307 >>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes
Georg Brandl6911e3c2007-09-04 07:15:32 +0000308 >>> print(sizeof(p), repr(p.raw))
Georg Brandl116aa622007-08-15 14:28:22 +0000309 3 '\x00\x00\x00'
310 >>> p = create_string_buffer("Hello") # create a buffer containing a NUL terminated string
Georg Brandl6911e3c2007-09-04 07:15:32 +0000311 >>> print(sizeof(p), repr(p.raw))
Georg Brandl116aa622007-08-15 14:28:22 +0000312 6 'Hello\x00'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000313 >>> print(repr(p.value))
Georg Brandl116aa622007-08-15 14:28:22 +0000314 'Hello'
315 >>> p = create_string_buffer("Hello", 10) # create a 10 byte buffer
Georg Brandl6911e3c2007-09-04 07:15:32 +0000316 >>> print(sizeof(p), repr(p.raw))
Georg Brandl116aa622007-08-15 14:28:22 +0000317 10 'Hello\x00\x00\x00\x00\x00'
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000318 >>> p.value = "Hi"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000319 >>> print(sizeof(p), repr(p.raw))
Georg Brandl116aa622007-08-15 14:28:22 +0000320 10 'Hi\x00lo\x00\x00\x00\x00\x00'
321 >>>
322
323The ``create_string_buffer`` function replaces the ``c_buffer`` function (which
324is still available as an alias), as well as the ``c_string`` function from
325earlier ctypes releases. To create a mutable memory block containing unicode
326characters of the C type ``wchar_t`` use the ``create_unicode_buffer`` function.
327
328
329.. _ctypes-calling-functions-continued:
330
331Calling functions, continued
332^^^^^^^^^^^^^^^^^^^^^^^^^^^^
333
334Note that printf prints to the real standard output channel, *not* to
335``sys.stdout``, so these examples will only work at the console prompt, not from
336within *IDLE* or *PythonWin*::
337
338 >>> printf = libc.printf
339 >>> printf("Hello, %s\n", "World!")
340 Hello, World!
341 14
342 >>> printf("Hello, %S", u"World!")
343 Hello, World!
344 13
345 >>> printf("%d bottles of beer\n", 42)
346 42 bottles of beer
347 19
348 >>> printf("%f bottles of beer\n", 42.5)
349 Traceback (most recent call last):
350 File "<stdin>", line 1, in ?
351 ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2
352 >>>
353
354As has been mentioned before, all Python types except integers, strings, and
355unicode strings have to be wrapped in their corresponding ``ctypes`` type, so
356that they can be converted to the required C data type::
357
358 >>> printf("An int %d, a double %f\n", 1234, c_double(3.14))
359 Integer 1234, double 3.1400001049
360 31
361 >>>
362
363
364.. _ctypes-calling-functions-with-own-custom-data-types:
365
366Calling functions with your own custom data types
367^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
368
369You can also customize ``ctypes`` argument conversion to allow instances of your
370own classes be used as function arguments. ``ctypes`` looks for an
371:attr:`_as_parameter_` attribute and uses this as the function argument. Of
372course, it must be one of integer, string, or unicode::
373
374 >>> class Bottles(object):
375 ... def __init__(self, number):
376 ... self._as_parameter_ = number
377 ...
378 >>> bottles = Bottles(42)
379 >>> printf("%d bottles of beer\n", bottles)
380 42 bottles of beer
381 19
382 >>>
383
384If you don't want to store the instance's data in the :attr:`_as_parameter_`
385instance variable, you could define a ``property`` which makes the data
Thomas Woutersed03b412007-08-28 21:37:11 +0000386available.
Georg Brandl116aa622007-08-15 14:28:22 +0000387
388
389.. _ctypes-specifying-required-argument-types:
390
391Specifying the required argument types (function prototypes)
392^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
393
394It is possible to specify the required argument types of functions exported from
395DLLs by setting the :attr:`argtypes` attribute.
396
397:attr:`argtypes` must be a sequence of C data types (the ``printf`` function is
398probably not a good example here, because it takes a variable number and
399different types of parameters depending on the format string, on the other hand
400this is quite handy to experiment with this feature)::
401
402 >>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
403 >>> printf("String '%s', Int %d, Double %f\n", "Hi", 10, 2.2)
404 String 'Hi', Int 10, Double 2.200000
405 37
406 >>>
407
408Specifying a format protects against incompatible argument types (just as a
409prototype for a C function), and tries to convert the arguments to valid types::
410
411 >>> printf("%d %d %d", 1, 2, 3)
412 Traceback (most recent call last):
413 File "<stdin>", line 1, in ?
414 ArgumentError: argument 2: exceptions.TypeError: wrong type
415 >>> printf("%s %d %f", "X", 2, 3)
416 X 2 3.00000012
417 12
418 >>>
419
420If you have defined your own classes which you pass to function calls, you have
421to implement a :meth:`from_param` class method for them to be able to use them
422in the :attr:`argtypes` sequence. The :meth:`from_param` class method receives
423the Python object passed to the function call, it should do a typecheck or
424whatever is needed to make sure this object is acceptable, and then return the
Thomas Heller2fadaa22008-06-16 19:56:33 +0000425object itself, its :attr:`_as_parameter_` attribute, or whatever you want to
Georg Brandl116aa622007-08-15 14:28:22 +0000426pass as the C function argument in this case. Again, the result should be an
Thomas Heller2fadaa22008-06-16 19:56:33 +0000427integer, string, unicode, a ``ctypes`` instance, or an object with an
Georg Brandl116aa622007-08-15 14:28:22 +0000428:attr:`_as_parameter_` attribute.
429
430
431.. _ctypes-return-types:
432
433Return types
434^^^^^^^^^^^^
435
436By default functions are assumed to return the C ``int`` type. Other return
437types can be specified by setting the :attr:`restype` attribute of the function
438object.
439
440Here is a more advanced example, it uses the ``strchr`` function, which expects
441a string pointer and a char, and returns a pointer to a string::
442
443 >>> strchr = libc.strchr
444 >>> strchr("abcdef", ord("d")) # doctest: +SKIP
445 8059983
446 >>> strchr.restype = c_char_p # c_char_p is a pointer to a string
447 >>> strchr("abcdef", ord("d"))
448 'def'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000449 >>> print(strchr("abcdef", ord("x")))
Georg Brandl116aa622007-08-15 14:28:22 +0000450 None
451 >>>
452
453If you want to avoid the ``ord("x")`` calls above, you can set the
454:attr:`argtypes` attribute, and the second argument will be converted from a
455single character Python string into a C char::
456
457 >>> strchr.restype = c_char_p
458 >>> strchr.argtypes = [c_char_p, c_char]
459 >>> strchr("abcdef", "d")
460 'def'
461 >>> strchr("abcdef", "def")
462 Traceback (most recent call last):
463 File "<stdin>", line 1, in ?
464 ArgumentError: argument 2: exceptions.TypeError: one character string expected
Georg Brandl6911e3c2007-09-04 07:15:32 +0000465 >>> print(strchr("abcdef", "x"))
Georg Brandl116aa622007-08-15 14:28:22 +0000466 None
467 >>> strchr("abcdef", "d")
468 'def'
469 >>>
470
471You can also use a callable Python object (a function or a class for example) as
472the :attr:`restype` attribute, if the foreign function returns an integer. The
473callable will be called with the ``integer`` the C function returns, and the
474result of this call will be used as the result of your function call. This is
475useful to check for error return values and automatically raise an exception::
476
477 >>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
478 >>> def ValidHandle(value):
479 ... if value == 0:
480 ... raise WinError()
481 ... return value
482 ...
483 >>>
484 >>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS
485 >>> GetModuleHandle(None) # doctest: +WINDOWS
486 486539264
487 >>> GetModuleHandle("something silly") # doctest: +WINDOWS
488 Traceback (most recent call last):
489 File "<stdin>", line 1, in ?
490 File "<stdin>", line 3, in ValidHandle
491 WindowsError: [Errno 126] The specified module could not be found.
492 >>>
493
494``WinError`` is a function which will call Windows ``FormatMessage()`` api to
495get the string representation of an error code, and *returns* an exception.
496``WinError`` takes an optional error code parameter, if no one is used, it calls
497:func:`GetLastError` to retrieve it.
498
499Please note that a much more powerful error checking mechanism is available
500through the :attr:`errcheck` attribute; see the reference manual for details.
501
502
503.. _ctypes-passing-pointers:
504
505Passing pointers (or: passing parameters by reference)
506^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
507
508Sometimes a C api function expects a *pointer* to a data type as parameter,
509probably to write into the corresponding location, or if the data is too large
510to be passed by value. This is also known as *passing parameters by reference*.
511
512``ctypes`` exports the :func:`byref` function which is used to pass parameters
513by reference. The same effect can be achieved with the ``pointer`` function,
514although ``pointer`` does a lot more work since it constructs a real pointer
515object, so it is faster to use :func:`byref` if you don't need the pointer
516object in Python itself::
517
518 >>> i = c_int()
519 >>> f = c_float()
520 >>> s = create_string_buffer('\000' * 32)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000521 >>> print(i.value, f.value, repr(s.value))
Georg Brandl116aa622007-08-15 14:28:22 +0000522 0 0.0 ''
523 >>> libc.sscanf("1 3.14 Hello", "%d %f %s",
524 ... byref(i), byref(f), s)
525 3
Georg Brandl6911e3c2007-09-04 07:15:32 +0000526 >>> print(i.value, f.value, repr(s.value))
Georg Brandl116aa622007-08-15 14:28:22 +0000527 1 3.1400001049 'Hello'
528 >>>
529
530
531.. _ctypes-structures-unions:
532
533Structures and unions
534^^^^^^^^^^^^^^^^^^^^^
535
536Structures and unions must derive from the :class:`Structure` and :class:`Union`
537base classes which are defined in the ``ctypes`` module. Each subclass must
538define a :attr:`_fields_` attribute. :attr:`_fields_` must be a list of
539*2-tuples*, containing a *field name* and a *field type*.
540
541The field type must be a ``ctypes`` type like :class:`c_int`, or any other
542derived ``ctypes`` type: structure, union, array, pointer.
543
544Here is a simple example of a POINT structure, which contains two integers named
545``x`` and ``y``, and also shows how to initialize a structure in the
546constructor::
547
548 >>> from ctypes import *
549 >>> class POINT(Structure):
550 ... _fields_ = [("x", c_int),
551 ... ("y", c_int)]
552 ...
553 >>> point = POINT(10, 20)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000554 >>> print(point.x, point.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000555 10 20
556 >>> point = POINT(y=5)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000557 >>> print(point.x, point.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000558 0 5
559 >>> POINT(1, 2, 3)
560 Traceback (most recent call last):
561 File "<stdin>", line 1, in ?
562 ValueError: too many initializers
563 >>>
564
565You can, however, build much more complicated structures. Structures can itself
566contain other structures by using a structure as a field type.
567
568Here is a RECT structure which contains two POINTs named ``upperleft`` and
569``lowerright`` ::
570
571 >>> class RECT(Structure):
572 ... _fields_ = [("upperleft", POINT),
573 ... ("lowerright", POINT)]
574 ...
575 >>> rc = RECT(point)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000576 >>> print(rc.upperleft.x, rc.upperleft.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000577 0 5
Georg Brandl6911e3c2007-09-04 07:15:32 +0000578 >>> print(rc.lowerright.x, rc.lowerright.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000579 0 0
580 >>>
581
582Nested structures can also be initialized in the constructor in several ways::
583
584 >>> r = RECT(POINT(1, 2), POINT(3, 4))
585 >>> r = RECT((1, 2), (3, 4))
586
Georg Brandl9afde1c2007-11-01 20:32:30 +0000587Field :term:`descriptor`\s can be retrieved from the *class*, they are useful
588for debugging because they can provide useful information::
Georg Brandl116aa622007-08-15 14:28:22 +0000589
Georg Brandl6911e3c2007-09-04 07:15:32 +0000590 >>> print(POINT.x)
Georg Brandl116aa622007-08-15 14:28:22 +0000591 <Field type=c_long, ofs=0, size=4>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000592 >>> print(POINT.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000593 <Field type=c_long, ofs=4, size=4>
594 >>>
595
596
597.. _ctypes-structureunion-alignment-byte-order:
598
599Structure/union alignment and byte order
600^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
601
602By default, Structure and Union fields are aligned in the same way the C
Thomas Woutersed03b412007-08-28 21:37:11 +0000603compiler does it. It is possible to override this behavior be specifying a
Georg Brandl116aa622007-08-15 14:28:22 +0000604:attr:`_pack_` class attribute in the subclass definition. This must be set to a
605positive integer and specifies the maximum alignment for the fields. This is
606what ``#pragma pack(n)`` also does in MSVC.
607
608``ctypes`` uses the native byte order for Structures and Unions. To build
609structures with non-native byte order, you can use one of the
610BigEndianStructure, LittleEndianStructure, BigEndianUnion, and LittleEndianUnion
611base classes. These classes cannot contain pointer fields.
612
613
614.. _ctypes-bit-fields-in-structures-unions:
615
616Bit fields in structures and unions
617^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
618
619It is possible to create structures and unions containing bit fields. Bit fields
620are only possible for integer fields, the bit width is specified as the third
621item in the :attr:`_fields_` tuples::
622
623 >>> class Int(Structure):
624 ... _fields_ = [("first_16", c_int, 16),
625 ... ("second_16", c_int, 16)]
626 ...
Georg Brandl6911e3c2007-09-04 07:15:32 +0000627 >>> print(Int.first_16)
Georg Brandl116aa622007-08-15 14:28:22 +0000628 <Field type=c_long, ofs=0:0, bits=16>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000629 >>> print(Int.second_16)
Georg Brandl116aa622007-08-15 14:28:22 +0000630 <Field type=c_long, ofs=0:16, bits=16>
631 >>>
632
633
634.. _ctypes-arrays:
635
636Arrays
637^^^^^^
638
639Arrays are sequences, containing a fixed number of instances of the same type.
640
641The recommended way to create array types is by multiplying a data type with a
642positive integer::
643
644 TenPointsArrayType = POINT * 10
645
Thomas Woutersed03b412007-08-28 21:37:11 +0000646Here is an example of an somewhat artificial data type, a structure containing 4
Georg Brandl116aa622007-08-15 14:28:22 +0000647POINTs among other stuff::
648
649 >>> from ctypes import *
650 >>> class POINT(Structure):
651 ... _fields_ = ("x", c_int), ("y", c_int)
652 ...
653 >>> class MyStruct(Structure):
654 ... _fields_ = [("a", c_int),
655 ... ("b", c_float),
656 ... ("point_array", POINT * 4)]
657 >>>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000658 >>> print(len(MyStruct().point_array))
Georg Brandl116aa622007-08-15 14:28:22 +0000659 4
660 >>>
661
662Instances are created in the usual way, by calling the class::
663
664 arr = TenPointsArrayType()
665 for pt in arr:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000666 print(pt.x, pt.y)
Georg Brandl116aa622007-08-15 14:28:22 +0000667
668The above code print a series of ``0 0`` lines, because the array contents is
669initialized to zeros.
670
671Initializers of the correct type can also be specified::
672
673 >>> from ctypes import *
674 >>> TenIntegers = c_int * 10
675 >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000676 >>> print(ii)
Georg Brandl116aa622007-08-15 14:28:22 +0000677 <c_long_Array_10 object at 0x...>
Georg Brandl6911e3c2007-09-04 07:15:32 +0000678 >>> for i in ii: print(i, end=" ")
Georg Brandl116aa622007-08-15 14:28:22 +0000679 ...
680 1 2 3 4 5 6 7 8 9 10
681 >>>
682
683
684.. _ctypes-pointers:
685
686Pointers
687^^^^^^^^
688
689Pointer instances are created by calling the ``pointer`` function on a
690``ctypes`` type::
691
692 >>> from ctypes import *
693 >>> i = c_int(42)
694 >>> pi = pointer(i)
695 >>>
696
697Pointer instances have a ``contents`` attribute which returns the object to
698which the pointer points, the ``i`` object above::
699
700 >>> pi.contents
701 c_long(42)
702 >>>
703
704Note that ``ctypes`` does not have OOR (original object return), it constructs a
705new, equivalent object each time you retrieve an attribute::
706
707 >>> pi.contents is i
708 False
709 >>> pi.contents is pi.contents
710 False
711 >>>
712
713Assigning another :class:`c_int` instance to the pointer's contents attribute
714would cause the pointer to point to the memory location where this is stored::
715
716 >>> i = c_int(99)
717 >>> pi.contents = i
718 >>> pi.contents
719 c_long(99)
720 >>>
721
Thomas Heller2fadaa22008-06-16 19:56:33 +0000722.. XXX Document dereferencing pointers, and that it is preferred over the .contents attribute.
723
Georg Brandl116aa622007-08-15 14:28:22 +0000724Pointer instances can also be indexed with integers::
725
726 >>> pi[0]
727 99
728 >>>
729
730Assigning to an integer index changes the pointed to value::
731
Georg Brandl6911e3c2007-09-04 07:15:32 +0000732 >>> print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000733 c_long(99)
734 >>> pi[0] = 22
Georg Brandl6911e3c2007-09-04 07:15:32 +0000735 >>> print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000736 c_long(22)
737 >>>
738
739It is also possible to use indexes different from 0, but you must know what
740you're doing, just as in C: You can access or change arbitrary memory locations.
741Generally you only use this feature if you receive a pointer from a C function,
742and you *know* that the pointer actually points to an array instead of a single
743item.
744
745Behind the scenes, the ``pointer`` function does more than simply create pointer
746instances, it has to create pointer *types* first. This is done with the
747``POINTER`` function, which accepts any ``ctypes`` type, and returns a new
748type::
749
750 >>> PI = POINTER(c_int)
751 >>> PI
752 <class 'ctypes.LP_c_long'>
753 >>> PI(42)
754 Traceback (most recent call last):
755 File "<stdin>", line 1, in ?
756 TypeError: expected c_long instead of int
757 >>> PI(c_int(42))
758 <ctypes.LP_c_long object at 0x...>
759 >>>
760
761Calling the pointer type without an argument creates a ``NULL`` pointer.
762``NULL`` pointers have a ``False`` boolean value::
763
764 >>> null_ptr = POINTER(c_int)()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000765 >>> print(bool(null_ptr))
Georg Brandl116aa622007-08-15 14:28:22 +0000766 False
767 >>>
768
769``ctypes`` checks for ``NULL`` when dereferencing pointers (but dereferencing
Thomas Heller2fadaa22008-06-16 19:56:33 +0000770invalid non-\ ``NULL`` pointers would crash Python)::
Georg Brandl116aa622007-08-15 14:28:22 +0000771
772 >>> null_ptr[0]
773 Traceback (most recent call last):
774 ....
775 ValueError: NULL pointer access
776 >>>
777
778 >>> null_ptr[0] = 1234
779 Traceback (most recent call last):
780 ....
781 ValueError: NULL pointer access
782 >>>
783
784
785.. _ctypes-type-conversions:
786
787Type conversions
788^^^^^^^^^^^^^^^^
789
790Usually, ctypes does strict type checking. This means, if you have
791``POINTER(c_int)`` in the :attr:`argtypes` list of a function or as the type of
792a member field in a structure definition, only instances of exactly the same
793type are accepted. There are some exceptions to this rule, where ctypes accepts
794other objects. For example, you can pass compatible array instances instead of
795pointer types. So, for ``POINTER(c_int)``, ctypes accepts an array of c_int::
796
797 >>> class Bar(Structure):
798 ... _fields_ = [("count", c_int), ("values", POINTER(c_int))]
799 ...
800 >>> bar = Bar()
801 >>> bar.values = (c_int * 3)(1, 2, 3)
802 >>> bar.count = 3
803 >>> for i in range(bar.count):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000804 ... print(bar.values[i])
Georg Brandl116aa622007-08-15 14:28:22 +0000805 ...
806 1
807 2
808 3
809 >>>
810
811To set a POINTER type field to ``NULL``, you can assign ``None``::
812
813 >>> bar.values = None
814 >>>
815
Thomas Heller2fadaa22008-06-16 19:56:33 +0000816.. XXX list other conversions...
Georg Brandl116aa622007-08-15 14:28:22 +0000817
Thomas Heller2fadaa22008-06-16 19:56:33 +0000818Sometimes you have instances of incompatible types. In C, you can cast one
Georg Brandl116aa622007-08-15 14:28:22 +0000819type into another type. ``ctypes`` provides a ``cast`` function which can be
820used in the same way. The ``Bar`` structure defined above accepts
821``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field,
822but not instances of other types::
823
824 >>> bar.values = (c_byte * 4)()
825 Traceback (most recent call last):
826 File "<stdin>", line 1, in ?
827 TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
828 >>>
829
830For these cases, the ``cast`` function is handy.
831
832The ``cast`` function can be used to cast a ctypes instance into a pointer to a
833different ctypes data type. ``cast`` takes two parameters, a ctypes object that
834is or can be converted to a pointer of some kind, and a ctypes pointer type. It
835returns an instance of the second argument, which references the same memory
836block as the first argument::
837
838 >>> a = (c_byte * 4)()
839 >>> cast(a, POINTER(c_int))
840 <ctypes.LP_c_long object at ...>
841 >>>
842
843So, ``cast`` can be used to assign to the ``values`` field of ``Bar`` the
844structure::
845
846 >>> bar = Bar()
847 >>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
Georg Brandl6911e3c2007-09-04 07:15:32 +0000848 >>> print(bar.values[0])
Georg Brandl116aa622007-08-15 14:28:22 +0000849 0
850 >>>
851
852
853.. _ctypes-incomplete-types:
854
855Incomplete Types
856^^^^^^^^^^^^^^^^
857
858*Incomplete Types* are structures, unions or arrays whose members are not yet
859specified. In C, they are specified by forward declarations, which are defined
860later::
861
862 struct cell; /* forward declaration */
863
864 struct {
865 char *name;
866 struct cell *next;
867 } cell;
868
869The straightforward translation into ctypes code would be this, but it does not
870work::
871
872 >>> class cell(Structure):
873 ... _fields_ = [("name", c_char_p),
874 ... ("next", POINTER(cell))]
875 ...
876 Traceback (most recent call last):
877 File "<stdin>", line 1, in ?
878 File "<stdin>", line 2, in cell
879 NameError: name 'cell' is not defined
880 >>>
881
882because the new ``class cell`` is not available in the class statement itself.
883In ``ctypes``, we can define the ``cell`` class and set the :attr:`_fields_`
884attribute later, after the class statement::
885
886 >>> from ctypes import *
887 >>> class cell(Structure):
888 ... pass
889 ...
890 >>> cell._fields_ = [("name", c_char_p),
891 ... ("next", POINTER(cell))]
892 >>>
893
894Lets try it. We create two instances of ``cell``, and let them point to each
895other, and finally follow the pointer chain a few times::
896
897 >>> c1 = cell()
898 >>> c1.name = "foo"
899 >>> c2 = cell()
900 >>> c2.name = "bar"
901 >>> c1.next = pointer(c2)
902 >>> c2.next = pointer(c1)
903 >>> p = c1
904 >>> for i in range(8):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000905 ... print(p.name, end=" ")
Georg Brandl116aa622007-08-15 14:28:22 +0000906 ... p = p.next[0]
907 ...
908 foo bar foo bar foo bar foo bar
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000909 >>>
Georg Brandl116aa622007-08-15 14:28:22 +0000910
911
912.. _ctypes-callback-functions:
913
914Callback functions
915^^^^^^^^^^^^^^^^^^
916
917``ctypes`` allows to create C callable function pointers from Python callables.
918These are sometimes called *callback functions*.
919
920First, you must create a class for the callback function, the class knows the
921calling convention, the return type, and the number and types of arguments this
922function will receive.
923
924The CFUNCTYPE factory function creates types for callback functions using the
925normal cdecl calling convention, and, on Windows, the WINFUNCTYPE factory
926function creates types for callback functions using the stdcall calling
927convention.
928
929Both of these factory functions are called with the result type as first
930argument, and the callback functions expected argument types as the remaining
931arguments.
932
933I will present an example here which uses the standard C library's :func:`qsort`
934function, this is used to sort items with the help of a callback function.
935:func:`qsort` will be used to sort an array of integers::
936
937 >>> IntArray5 = c_int * 5
938 >>> ia = IntArray5(5, 1, 7, 33, 99)
939 >>> qsort = libc.qsort
940 >>> qsort.restype = None
941 >>>
942
943:func:`qsort` must be called with a pointer to the data to sort, the number of
944items in the data array, the size of one item, and a pointer to the comparison
945function, the callback. The callback will then be called with two pointers to
946items, and it must return a negative integer if the first item is smaller than
947the second, a zero if they are equal, and a positive integer else.
948
949So our callback function receives pointers to integers, and must return an
950integer. First we create the ``type`` for the callback function::
951
952 >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
953 >>>
954
955For the first implementation of the callback function, we simply print the
956arguments we get, and return 0 (incremental development ;-)::
957
958 >>> def py_cmp_func(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000959 ... print("py_cmp_func", a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000960 ... return 0
961 ...
962 >>>
963
964Create the C callable callback::
965
966 >>> cmp_func = CMPFUNC(py_cmp_func)
967 >>>
968
969And we're ready to go::
970
971 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
972 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
973 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
974 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
975 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
976 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
977 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
978 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
979 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
980 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
981 py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
982 >>>
983
984We know how to access the contents of a pointer, so lets redefine our callback::
985
986 >>> def py_cmp_func(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000987 ... print("py_cmp_func", a[0], b[0])
Georg Brandl116aa622007-08-15 14:28:22 +0000988 ... return 0
989 ...
990 >>> cmp_func = CMPFUNC(py_cmp_func)
991 >>>
992
993Here is what we get on Windows::
994
995 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
996 py_cmp_func 7 1
997 py_cmp_func 33 1
998 py_cmp_func 99 1
999 py_cmp_func 5 1
1000 py_cmp_func 7 5
1001 py_cmp_func 33 5
1002 py_cmp_func 99 5
1003 py_cmp_func 7 99
1004 py_cmp_func 33 99
1005 py_cmp_func 7 33
1006 >>>
1007
1008It is funny to see that on linux the sort function seems to work much more
1009efficient, it is doing less comparisons::
1010
1011 >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX
1012 py_cmp_func 5 1
1013 py_cmp_func 33 99
1014 py_cmp_func 7 33
1015 py_cmp_func 5 7
1016 py_cmp_func 1 7
1017 >>>
1018
1019Ah, we're nearly done! The last step is to actually compare the two items and
1020return a useful result::
1021
1022 >>> def py_cmp_func(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +00001023 ... print("py_cmp_func", a[0], b[0])
Georg Brandl116aa622007-08-15 14:28:22 +00001024 ... return a[0] - b[0]
1025 ...
1026 >>>
1027
1028Final run on Windows::
1029
1030 >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +WINDOWS
1031 py_cmp_func 33 7
1032 py_cmp_func 99 33
1033 py_cmp_func 5 99
1034 py_cmp_func 1 99
1035 py_cmp_func 33 7
1036 py_cmp_func 1 33
1037 py_cmp_func 5 33
1038 py_cmp_func 5 7
1039 py_cmp_func 1 7
1040 py_cmp_func 5 1
1041 >>>
1042
1043and on Linux::
1044
1045 >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX
1046 py_cmp_func 5 1
1047 py_cmp_func 33 99
1048 py_cmp_func 7 33
1049 py_cmp_func 1 7
1050 py_cmp_func 5 7
1051 >>>
1052
1053It is quite interesting to see that the Windows :func:`qsort` function needs
1054more comparisons than the linux version!
1055
1056As we can easily check, our array is sorted now::
1057
Georg Brandl6911e3c2007-09-04 07:15:32 +00001058 >>> for i in ia: print(i, end=" ")
Georg Brandl116aa622007-08-15 14:28:22 +00001059 ...
1060 1 5 7 33 99
1061 >>>
1062
1063**Important note for callback functions:**
1064
1065Make sure you keep references to CFUNCTYPE objects as long as they are used from
1066C code. ``ctypes`` doesn't, and if you don't, they may be garbage collected,
1067crashing your program when a callback is made.
1068
1069
1070.. _ctypes-accessing-values-exported-from-dlls:
1071
1072Accessing values exported from dlls
1073^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1074
Thomas Heller2fadaa22008-06-16 19:56:33 +00001075Some shared libraries not only export functions, they also export variables. An
Georg Brandl116aa622007-08-15 14:28:22 +00001076example in the Python library itself is the ``Py_OptimizeFlag``, an integer set
1077to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on
1078startup.
1079
1080``ctypes`` can access values like this with the :meth:`in_dll` class methods of
1081the type. *pythonapi* is a predefined symbol giving access to the Python C
1082api::
1083
1084 >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
Georg Brandl6911e3c2007-09-04 07:15:32 +00001085 >>> print(opt_flag)
Georg Brandl116aa622007-08-15 14:28:22 +00001086 c_long(0)
1087 >>>
1088
1089If the interpreter would have been started with :option:`-O`, the sample would
1090have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been
1091specified.
1092
1093An extended example which also demonstrates the use of pointers accesses the
1094``PyImport_FrozenModules`` pointer exported by Python.
1095
1096Quoting the Python docs: *This pointer is initialized to point to an array of
1097"struct _frozen" records, terminated by one whose members are all NULL or zero.
1098When a frozen module is imported, it is searched in this table. Third-party code
1099could play tricks with this to provide a dynamically created collection of
1100frozen modules.*
1101
1102So manipulating this pointer could even prove useful. To restrict the example
1103size, we show only how this table can be read with ``ctypes``::
1104
1105 >>> from ctypes import *
1106 >>>
1107 >>> class struct_frozen(Structure):
1108 ... _fields_ = [("name", c_char_p),
1109 ... ("code", POINTER(c_ubyte)),
1110 ... ("size", c_int)]
1111 ...
1112 >>>
1113
1114We have defined the ``struct _frozen`` data type, so we can get the pointer to
1115the table::
1116
1117 >>> FrozenTable = POINTER(struct_frozen)
1118 >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
1119 >>>
1120
1121Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we
1122can iterate over it, but we just have to make sure that our loop terminates,
1123because pointers have no size. Sooner or later it would probably crash with an
1124access violation or whatever, so it's better to break out of the loop when we
1125hit the NULL entry::
1126
1127 >>> for item in table:
Georg Brandl6911e3c2007-09-04 07:15:32 +00001128 ... print(item.name, item.size)
Georg Brandl116aa622007-08-15 14:28:22 +00001129 ... if item.name is None:
1130 ... break
1131 ...
1132 __hello__ 104
1133 __phello__ -104
1134 __phello__.spam 104
1135 None 0
1136 >>>
1137
1138The fact that standard Python has a frozen module and a frozen package
Thomas Woutersed03b412007-08-28 21:37:11 +00001139(indicated by the negative size member) is not well known, it is only used for
Georg Brandl116aa622007-08-15 14:28:22 +00001140testing. Try it out with ``import __hello__`` for example.
1141
1142
1143.. _ctypes-surprises:
1144
1145Surprises
1146^^^^^^^^^
1147
1148There are some edges in ``ctypes`` where you may be expect something else than
1149what actually happens.
1150
1151Consider the following example::
1152
1153 >>> from ctypes import *
1154 >>> class POINT(Structure):
1155 ... _fields_ = ("x", c_int), ("y", c_int)
1156 ...
1157 >>> class RECT(Structure):
1158 ... _fields_ = ("a", POINT), ("b", POINT)
1159 ...
1160 >>> p1 = POINT(1, 2)
1161 >>> p2 = POINT(3, 4)
1162 >>> rc = RECT(p1, p2)
Georg Brandl6911e3c2007-09-04 07:15:32 +00001163 >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
Georg Brandl116aa622007-08-15 14:28:22 +00001164 1 2 3 4
1165 >>> # now swap the two points
1166 >>> rc.a, rc.b = rc.b, rc.a
Georg Brandl6911e3c2007-09-04 07:15:32 +00001167 >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
Georg Brandl116aa622007-08-15 14:28:22 +00001168 3 4 3 4
1169 >>>
1170
1171Hm. We certainly expected the last statement to print ``3 4 1 2``. What
Thomas Woutersed03b412007-08-28 21:37:11 +00001172happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
Georg Brandl116aa622007-08-15 14:28:22 +00001173
1174 >>> temp0, temp1 = rc.b, rc.a
1175 >>> rc.a = temp0
1176 >>> rc.b = temp1
1177 >>>
1178
1179Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of
1180the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer
1181contents of ``temp0`` into ``rc`` 's buffer. This, in turn, changes the
1182contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have
1183the expected effect.
1184
Thomas Woutersed03b412007-08-28 21:37:11 +00001185Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
1186doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing
Georg Brandl116aa622007-08-15 14:28:22 +00001187the root-object's underlying buffer.
1188
1189Another example that may behave different from what one would expect is this::
1190
1191 >>> s = c_char_p()
1192 >>> s.value = "abc def ghi"
1193 >>> s.value
1194 'abc def ghi'
1195 >>> s.value is s.value
1196 False
1197 >>>
1198
1199Why is it printing ``False``? ctypes instances are objects containing a memory
Georg Brandl9afde1c2007-11-01 20:32:30 +00001200block plus some :term:`descriptor`\s accessing the contents of the memory.
1201Storing a Python object in the memory block does not store the object itself,
1202instead the ``contents`` of the object is stored. Accessing the contents again
1203constructs a new Python object each time!
Georg Brandl116aa622007-08-15 14:28:22 +00001204
1205
1206.. _ctypes-variable-sized-data-types:
1207
1208Variable-sized data types
1209^^^^^^^^^^^^^^^^^^^^^^^^^
1210
1211``ctypes`` provides some support for variable-sized arrays and structures (this
1212was added in version 0.9.9.7).
1213
1214The ``resize`` function can be used to resize the memory buffer of an existing
1215ctypes object. The function takes the object as first argument, and the
1216requested size in bytes as the second argument. The memory block cannot be made
1217smaller than the natural memory block specified by the objects type, a
1218``ValueError`` is raised if this is tried::
1219
1220 >>> short_array = (c_short * 4)()
Georg Brandl6911e3c2007-09-04 07:15:32 +00001221 >>> print(sizeof(short_array))
Georg Brandl116aa622007-08-15 14:28:22 +00001222 8
1223 >>> resize(short_array, 4)
1224 Traceback (most recent call last):
1225 ...
1226 ValueError: minimum size is 8
1227 >>> resize(short_array, 32)
1228 >>> sizeof(short_array)
1229 32
1230 >>> sizeof(type(short_array))
1231 8
1232 >>>
1233
1234This is nice and fine, but how would one access the additional elements
1235contained in this array? Since the type still only knows about 4 elements, we
1236get errors accessing other elements::
1237
1238 >>> short_array[:]
1239 [0, 0, 0, 0]
1240 >>> short_array[7]
1241 Traceback (most recent call last):
1242 ...
1243 IndexError: invalid index
1244 >>>
1245
1246Another way to use variable-sized data types with ``ctypes`` is to use the
1247dynamic nature of Python, and (re-)define the data type after the required size
1248is already known, on a case by case basis.
1249
1250
Georg Brandl116aa622007-08-15 14:28:22 +00001251.. _ctypes-ctypes-reference:
1252
1253ctypes reference
1254----------------
1255
1256
1257.. _ctypes-finding-shared-libraries:
1258
1259Finding shared libraries
1260^^^^^^^^^^^^^^^^^^^^^^^^
1261
1262When programming in a compiled language, shared libraries are accessed when
1263compiling/linking a program, and when the program is run.
1264
1265The purpose of the ``find_library`` function is to locate a library in a way
1266similar to what the compiler does (on platforms with several versions of a
1267shared library the most recent should be loaded), while the ctypes library
1268loaders act like when a program is run, and call the runtime loader directly.
1269
1270The ``ctypes.util`` module provides a function which can help to determine the
1271library to load.
1272
1273
1274.. data:: find_library(name)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001275 :module: ctypes.util
Georg Brandl116aa622007-08-15 14:28:22 +00001276 :noindex:
1277
1278 Try to find a library and return a pathname. *name* is the library name without
1279 any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this
1280 is the form used for the posix linker option :option:`-l`). If no library can
1281 be found, returns ``None``.
1282
Thomas Woutersed03b412007-08-28 21:37:11 +00001283The exact functionality is system dependent.
Georg Brandl116aa622007-08-15 14:28:22 +00001284
1285On Linux, ``find_library`` tries to run external programs (/sbin/ldconfig, gcc,
1286and objdump) to find the library file. It returns the filename of the library
Thomas Woutersed03b412007-08-28 21:37:11 +00001287file. Here are some examples::
Georg Brandl116aa622007-08-15 14:28:22 +00001288
1289 >>> from ctypes.util import find_library
1290 >>> find_library("m")
1291 'libm.so.6'
1292 >>> find_library("c")
1293 'libc.so.6'
1294 >>> find_library("bz2")
1295 'libbz2.so.1.0'
1296 >>>
1297
1298On OS X, ``find_library`` tries several predefined naming schemes and paths to
Thomas Woutersed03b412007-08-28 21:37:11 +00001299locate the library, and returns a full pathname if successful::
Georg Brandl116aa622007-08-15 14:28:22 +00001300
1301 >>> from ctypes.util import find_library
1302 >>> find_library("c")
1303 '/usr/lib/libc.dylib'
1304 >>> find_library("m")
1305 '/usr/lib/libm.dylib'
1306 >>> find_library("bz2")
1307 '/usr/lib/libbz2.dylib'
1308 >>> find_library("AGL")
1309 '/System/Library/Frameworks/AGL.framework/AGL'
1310 >>>
1311
1312On Windows, ``find_library`` searches along the system search path, and returns
1313the full pathname, but since there is no predefined naming scheme a call like
1314``find_library("c")`` will fail and return ``None``.
1315
1316If wrapping a shared library with ``ctypes``, it *may* be better to determine
1317the shared library name at development type, and hardcode that into the wrapper
1318module instead of using ``find_library`` to locate the library at runtime.
1319
1320
1321.. _ctypes-loading-shared-libraries:
1322
1323Loading shared libraries
1324^^^^^^^^^^^^^^^^^^^^^^^^
1325
1326There are several ways to loaded shared libraries into the Python process. One
1327way is to instantiate one of the following classes:
1328
1329
Thomas Hellerb795f5282008-06-10 15:26:58 +00001330.. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001331
1332 Instances of this class represent loaded shared libraries. Functions in these
1333 libraries use the standard C calling convention, and are assumed to return
1334 ``int``.
1335
1336
Thomas Hellerb795f5282008-06-10 15:26:58 +00001337.. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001338
1339 Windows only: Instances of this class represent loaded shared libraries,
1340 functions in these libraries use the ``stdcall`` calling convention, and are
1341 assumed to return the windows specific :class:`HRESULT` code. :class:`HRESULT`
1342 values contain information specifying whether the function call failed or
1343 succeeded, together with additional error code. If the return value signals a
1344 failure, an :class:`WindowsError` is automatically raised.
1345
1346
Thomas Hellerb795f5282008-06-10 15:26:58 +00001347.. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001348
1349 Windows only: Instances of this class represent loaded shared libraries,
1350 functions in these libraries use the ``stdcall`` calling convention, and are
1351 assumed to return ``int`` by default.
1352
1353 On Windows CE only the standard calling convention is used, for convenience the
1354 :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this
1355 platform.
1356
Georg Brandl9afde1c2007-11-01 20:32:30 +00001357The Python :term:`global interpreter lock` is released before calling any
1358function exported by these libraries, and reacquired afterwards.
Georg Brandl116aa622007-08-15 14:28:22 +00001359
1360
1361.. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)
1362
1363 Instances of this class behave like :class:`CDLL` instances, except that the
1364 Python GIL is *not* released during the function call, and after the function
1365 execution the Python error flag is checked. If the error flag is set, a Python
1366 exception is raised.
1367
1368 Thus, this is only useful to call Python C api functions directly.
1369
1370All these classes can be instantiated by calling them with at least one
1371argument, the pathname of the shared library. If you have an existing handle to
Benjamin Peterson4469d0c2008-11-30 22:46:23 +00001372an already loaded shared library, it can be passed as the ``handle`` named
Georg Brandl116aa622007-08-15 14:28:22 +00001373parameter, otherwise the underlying platforms ``dlopen`` or :meth:`LoadLibrary`
1374function is used to load the library into the process, and to get a handle to
1375it.
1376
1377The *mode* parameter can be used to specify how the library is loaded. For
1378details, consult the ``dlopen(3)`` manpage, on Windows, *mode* is ignored.
1379
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001380The *use_errno* parameter, when set to True, enables a ctypes mechanism that
1381allows to access the system :data:`errno` error number in a safe way.
1382:mod:`ctypes` maintains a thread-local copy of the systems :data:`errno`
1383variable; if you call foreign functions created with ``use_errno=True`` then the
1384:data:`errno` value before the function call is swapped with the ctypes private
1385copy, the same happens immediately after the function call.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001386
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001387The function :func:`ctypes.get_errno` returns the value of the ctypes private
1388copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy
1389to a new value and returns the former value.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001390
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001391The *use_last_error* parameter, when set to True, enables the same mechanism for
1392the Windows error code which is managed by the :func:`GetLastError` and
1393:func:`SetLastError` Windows API functions; :func:`ctypes.get_last_error` and
1394:func:`ctypes.set_last_error` are used to request and change the ctypes private
1395copy of the windows error code.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001396
Georg Brandl116aa622007-08-15 14:28:22 +00001397.. data:: RTLD_GLOBAL
1398 :noindex:
1399
1400 Flag to use as *mode* parameter. On platforms where this flag is not available,
1401 it is defined as the integer zero.
1402
1403
1404.. data:: RTLD_LOCAL
1405 :noindex:
1406
1407 Flag to use as *mode* parameter. On platforms where this is not available, it
1408 is the same as *RTLD_GLOBAL*.
1409
1410
1411.. data:: DEFAULT_MODE
1412 :noindex:
1413
1414 The default mode which is used to load shared libraries. On OSX 10.3, this is
1415 *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*.
1416
1417Instances of these classes have no public methods, however :meth:`__getattr__`
Thomas Woutersed03b412007-08-28 21:37:11 +00001418and :meth:`__getitem__` have special behavior: functions exported by the shared
Georg Brandl116aa622007-08-15 14:28:22 +00001419library can be accessed as attributes of by index. Please note that both
1420:meth:`__getattr__` and :meth:`__getitem__` cache their result, so calling them
1421repeatedly returns the same object each time.
1422
1423The following public attributes are available, their name starts with an
1424underscore to not clash with exported function names:
1425
1426
1427.. attribute:: PyDLL._handle
1428
1429 The system handle used to access the library.
1430
1431
1432.. attribute:: PyDLL._name
1433
Thomas Woutersed03b412007-08-28 21:37:11 +00001434 The name of the library passed in the constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001435
1436Shared libraries can also be loaded by using one of the prefabricated objects,
1437which are instances of the :class:`LibraryLoader` class, either by calling the
1438:meth:`LoadLibrary` method, or by retrieving the library as attribute of the
1439loader instance.
1440
1441
1442.. class:: LibraryLoader(dlltype)
1443
1444 Class which loads shared libraries. ``dlltype`` should be one of the
1445 :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types.
1446
Thomas Woutersed03b412007-08-28 21:37:11 +00001447 :meth:`__getattr__` has special behavior: It allows to load a shared library by
Georg Brandl116aa622007-08-15 14:28:22 +00001448 accessing it as attribute of a library loader instance. The result is cached,
1449 so repeated attribute accesses return the same library each time.
1450
1451
Benjamin Petersone41251e2008-04-25 01:59:09 +00001452 .. method:: LoadLibrary(name)
Georg Brandl116aa622007-08-15 14:28:22 +00001453
Benjamin Petersone41251e2008-04-25 01:59:09 +00001454 Load a shared library into the process and return it. This method always
1455 returns a new instance of the library.
Georg Brandl116aa622007-08-15 14:28:22 +00001456
1457These prefabricated library loaders are available:
1458
1459
1460.. data:: cdll
1461 :noindex:
1462
1463 Creates :class:`CDLL` instances.
1464
1465
1466.. data:: windll
1467 :noindex:
1468
1469 Windows only: Creates :class:`WinDLL` instances.
1470
1471
1472.. data:: oledll
1473 :noindex:
1474
1475 Windows only: Creates :class:`OleDLL` instances.
1476
1477
1478.. data:: pydll
1479 :noindex:
1480
1481 Creates :class:`PyDLL` instances.
1482
1483For accessing the C Python api directly, a ready-to-use Python shared library
1484object is available:
1485
1486
1487.. data:: pythonapi
1488 :noindex:
1489
1490 An instance of :class:`PyDLL` that exposes Python C api functions as attributes.
1491 Note that all these functions are assumed to return C ``int``, which is of
1492 course not always the truth, so you have to assign the correct :attr:`restype`
1493 attribute to use these functions.
1494
1495
1496.. _ctypes-foreign-functions:
1497
1498Foreign functions
1499^^^^^^^^^^^^^^^^^
1500
1501As explained in the previous section, foreign functions can be accessed as
1502attributes of loaded shared libraries. The function objects created in this way
1503by default accept any number of arguments, accept any ctypes data instances as
1504arguments, and return the default result type specified by the library loader.
1505They are instances of a private class:
1506
1507
1508.. class:: _FuncPtr
1509
1510 Base class for C callable foreign functions.
1511
Benjamin Petersone41251e2008-04-25 01:59:09 +00001512 Instances of foreign functions are also C compatible data types; they
1513 represent C function pointers.
Georg Brandl116aa622007-08-15 14:28:22 +00001514
Benjamin Petersone41251e2008-04-25 01:59:09 +00001515 This behavior can be customized by assigning to special attributes of the
1516 foreign function object.
Georg Brandl116aa622007-08-15 14:28:22 +00001517
1518
Benjamin Petersone41251e2008-04-25 01:59:09 +00001519 .. attribute:: restype
Georg Brandl116aa622007-08-15 14:28:22 +00001520
Benjamin Petersone41251e2008-04-25 01:59:09 +00001521 Assign a ctypes type to specify the result type of the foreign function.
1522 Use ``None`` for ``void`` a function not returning anything.
Georg Brandl116aa622007-08-15 14:28:22 +00001523
Benjamin Petersone41251e2008-04-25 01:59:09 +00001524 It is possible to assign a callable Python object that is not a ctypes
1525 type, in this case the function is assumed to return a C ``int``, and the
1526 callable will be called with this integer, allowing to do further
1527 processing or error checking. Using this is deprecated, for more flexible
1528 post processing or error checking use a ctypes data type as
1529 :attr:`restype` and assign a callable to the :attr:`errcheck` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001530
1531
Benjamin Petersone41251e2008-04-25 01:59:09 +00001532 .. attribute:: argtypes
Georg Brandl116aa622007-08-15 14:28:22 +00001533
Benjamin Petersone41251e2008-04-25 01:59:09 +00001534 Assign a tuple of ctypes types to specify the argument types that the
1535 function accepts. Functions using the ``stdcall`` calling convention can
1536 only be called with the same number of arguments as the length of this
1537 tuple; functions using the C calling convention accept additional,
1538 unspecified arguments as well.
Georg Brandl116aa622007-08-15 14:28:22 +00001539
Benjamin Petersone41251e2008-04-25 01:59:09 +00001540 When a foreign function is called, each actual argument is passed to the
1541 :meth:`from_param` class method of the items in the :attr:`argtypes`
1542 tuple, this method allows to adapt the actual argument to an object that
1543 the foreign function accepts. For example, a :class:`c_char_p` item in
1544 the :attr:`argtypes` tuple will convert a unicode string passed as
1545 argument into an byte string using ctypes conversion rules.
Georg Brandl116aa622007-08-15 14:28:22 +00001546
Benjamin Petersone41251e2008-04-25 01:59:09 +00001547 New: It is now possible to put items in argtypes which are not ctypes
1548 types, but each item must have a :meth:`from_param` method which returns a
1549 value usable as argument (integer, string, ctypes instance). This allows
1550 to define adapters that can adapt custom objects as function parameters.
Georg Brandl116aa622007-08-15 14:28:22 +00001551
1552
Benjamin Petersone41251e2008-04-25 01:59:09 +00001553 .. attribute:: errcheck
Georg Brandl116aa622007-08-15 14:28:22 +00001554
Benjamin Petersone41251e2008-04-25 01:59:09 +00001555 Assign a Python function or another callable to this attribute. The
1556 callable will be called with three or more arguments:
Georg Brandl116aa622007-08-15 14:28:22 +00001557
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001558 .. function:: callable(result, func, arguments)
1559 :noindex:
Georg Brandl116aa622007-08-15 14:28:22 +00001560
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001561 ``result`` is what the foreign function returns, as specified
1562 by the :attr:`restype` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001563
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001564 ``func`` is the foreign function object itself, this allows
1565 to reuse the same callable object to check or post process
1566 the results of several functions.
Georg Brandl116aa622007-08-15 14:28:22 +00001567
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001568 ``arguments`` is a tuple containing the parameters originally
1569 passed to the function call, this allows to specialize the
1570 behavior on the arguments used.
Georg Brandl116aa622007-08-15 14:28:22 +00001571
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001572 The object that this function returns will be returned from the
1573 foreign function call, but it can also check the result value
1574 and raise an exception if the foreign function call failed.
Georg Brandl116aa622007-08-15 14:28:22 +00001575
1576
1577.. exception:: ArgumentError()
1578
1579 This exception is raised when a foreign function call cannot convert one of the
1580 passed arguments.
1581
1582
1583.. _ctypes-function-prototypes:
1584
1585Function prototypes
1586^^^^^^^^^^^^^^^^^^^
1587
1588Foreign functions can also be created by instantiating function prototypes.
1589Function prototypes are similar to function prototypes in C; they describe a
1590function (return type, argument types, calling convention) without defining an
1591implementation. The factory functions must be called with the desired result
1592type and the argument types of the function.
1593
1594
Thomas Hellerb795f5282008-06-10 15:26:58 +00001595.. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001596
1597 The returned function prototype creates functions that use the standard C
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001598 calling convention. The function will release the GIL during the call. If
1599 *use_errno* is set to True, the ctypes private copy of the system
1600 :data:`errno` variable is exchanged with the real :data:`errno` value bafore
1601 and after the call; *use_last_error* does the same for the Windows error
1602 code.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001603
Georg Brandl116aa622007-08-15 14:28:22 +00001604
Thomas Hellerb795f5282008-06-10 15:26:58 +00001605.. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001606
1607 Windows only: The returned function prototype creates functions that use the
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001608 ``stdcall`` calling convention, except on Windows CE where
1609 :func:`WINFUNCTYPE` is the same as :func:`CFUNCTYPE`. The function will
1610 release the GIL during the call. *use_errno* and *use_last_error* have the
1611 same meaning as above.
Georg Brandl116aa622007-08-15 14:28:22 +00001612
1613
1614.. function:: PYFUNCTYPE(restype, *argtypes)
1615
1616 The returned function prototype creates functions that use the Python calling
1617 convention. The function will *not* release the GIL during the call.
1618
Thomas Heller2fadaa22008-06-16 19:56:33 +00001619Function prototypes created by these factory functions can be instantiated in
1620different ways, depending on the type and number of the parameters in the call:
Georg Brandl116aa622007-08-15 14:28:22 +00001621
1622
Thomas Heller2fadaa22008-06-16 19:56:33 +00001623 .. function:: prototype(address)
1624 :noindex:
1625 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001626
Thomas Heller2fadaa22008-06-16 19:56:33 +00001627 Returns a foreign function at the specified address which must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +00001628
1629
Thomas Heller2fadaa22008-06-16 19:56:33 +00001630 .. function:: prototype(callable)
1631 :noindex:
1632 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001633
Thomas Heller2fadaa22008-06-16 19:56:33 +00001634 Create a C callable function (a callback function) from a Python ``callable``.
Georg Brandl116aa622007-08-15 14:28:22 +00001635
1636
Thomas Heller2fadaa22008-06-16 19:56:33 +00001637 .. function:: prototype(func_spec[, paramflags])
1638 :noindex:
1639 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001640
Thomas Heller2fadaa22008-06-16 19:56:33 +00001641 Returns a foreign function exported by a shared library. ``func_spec`` must be a
1642 2-tuple ``(name_or_ordinal, library)``. The first item is the name of the
1643 exported function as string, or the ordinal of the exported function as small
1644 integer. The second item is the shared library instance.
Georg Brandl116aa622007-08-15 14:28:22 +00001645
1646
Thomas Heller2fadaa22008-06-16 19:56:33 +00001647 .. function:: prototype(vtbl_index, name[, paramflags[, iid]])
1648 :noindex:
1649 :module:
Georg Brandl116aa622007-08-15 14:28:22 +00001650
Thomas Heller2fadaa22008-06-16 19:56:33 +00001651 Returns a foreign function that will call a COM method. ``vtbl_index`` is the
1652 index into the virtual function table, a small non-negative integer. *name* is
1653 name of the COM method. *iid* is an optional pointer to the interface identifier
1654 which is used in extended error reporting.
Georg Brandl116aa622007-08-15 14:28:22 +00001655
Thomas Heller2fadaa22008-06-16 19:56:33 +00001656 COM methods use a special calling convention: They require a pointer to the COM
1657 interface as first argument, in addition to those parameters that are specified
1658 in the :attr:`argtypes` tuple.
Georg Brandl116aa622007-08-15 14:28:22 +00001659
Thomas Heller2fadaa22008-06-16 19:56:33 +00001660 The optional *paramflags* parameter creates foreign function wrappers with much
1661 more functionality than the features described above.
Georg Brandl116aa622007-08-15 14:28:22 +00001662
Thomas Heller2fadaa22008-06-16 19:56:33 +00001663 *paramflags* must be a tuple of the same length as :attr:`argtypes`.
Georg Brandl116aa622007-08-15 14:28:22 +00001664
Thomas Heller2fadaa22008-06-16 19:56:33 +00001665 Each item in this tuple contains further information about a parameter, it must
1666 be a tuple containing one, two, or three items.
Georg Brandl116aa622007-08-15 14:28:22 +00001667
Thomas Heller2fadaa22008-06-16 19:56:33 +00001668 The first item is an integer containing a combination of direction
1669 flags for the parameter:
Georg Brandl116aa622007-08-15 14:28:22 +00001670
Thomas Heller2fadaa22008-06-16 19:56:33 +00001671 1
1672 Specifies an input parameter to the function.
Georg Brandl116aa622007-08-15 14:28:22 +00001673
Thomas Heller2fadaa22008-06-16 19:56:33 +00001674 2
1675 Output parameter. The foreign function fills in a value.
Georg Brandl116aa622007-08-15 14:28:22 +00001676
Thomas Heller2fadaa22008-06-16 19:56:33 +00001677 4
1678 Input parameter which defaults to the integer zero.
Georg Brandl116aa622007-08-15 14:28:22 +00001679
Thomas Heller2fadaa22008-06-16 19:56:33 +00001680 The optional second item is the parameter name as string. If this is specified,
1681 the foreign function can be called with named parameters.
Georg Brandl116aa622007-08-15 14:28:22 +00001682
Thomas Heller2fadaa22008-06-16 19:56:33 +00001683 The optional third item is the default value for this parameter.
Georg Brandl116aa622007-08-15 14:28:22 +00001684
1685This example demonstrates how to wrap the Windows ``MessageBoxA`` function so
1686that it supports default parameters and named arguments. The C declaration from
1687the windows header file is this::
1688
1689 WINUSERAPI int WINAPI
1690 MessageBoxA(
1691 HWND hWnd ,
1692 LPCSTR lpText,
1693 LPCSTR lpCaption,
1694 UINT uType);
1695
Thomas Heller2fadaa22008-06-16 19:56:33 +00001696Here is the wrapping with ``ctypes``::
Georg Brandl116aa622007-08-15 14:28:22 +00001697
Thomas Heller2fadaa22008-06-16 19:56:33 +00001698 >>> from ctypes import c_int, WINFUNCTYPE, windll
1699 >>> from ctypes.wintypes import HWND, LPCSTR, UINT
1700 >>> prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
1701 >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
1702 >>> MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)
1703 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001704
1705The MessageBox foreign function can now be called in these ways::
1706
1707 >>> MessageBox()
1708 >>> MessageBox(text="Spam, spam, spam")
1709 >>> MessageBox(flags=2, text="foo bar")
1710 >>>
1711
1712A second example demonstrates output parameters. The win32 ``GetWindowRect``
1713function retrieves the dimensions of a specified window by copying them into
1714``RECT`` structure that the caller has to supply. Here is the C declaration::
1715
1716 WINUSERAPI BOOL WINAPI
1717 GetWindowRect(
1718 HWND hWnd,
1719 LPRECT lpRect);
1720
Thomas Heller2fadaa22008-06-16 19:56:33 +00001721Here is the wrapping with ``ctypes``::
Georg Brandl116aa622007-08-15 14:28:22 +00001722
Thomas Heller2fadaa22008-06-16 19:56:33 +00001723 >>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
1724 >>> from ctypes.wintypes import BOOL, HWND, RECT
1725 >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
1726 >>> paramflags = (1, "hwnd"), (2, "lprect")
1727 >>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
1728 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001729
1730Functions with output parameters will automatically return the output parameter
1731value if there is a single one, or a tuple containing the output parameter
1732values when there are more than one, so the GetWindowRect function now returns a
1733RECT instance, when called.
1734
1735Output parameters can be combined with the :attr:`errcheck` protocol to do
1736further output processing and error checking. The win32 ``GetWindowRect`` api
1737function returns a ``BOOL`` to signal success or failure, so this function could
1738do the error checking, and raises an exception when the api call failed::
1739
1740 >>> def errcheck(result, func, args):
1741 ... if not result:
1742 ... raise WinError()
1743 ... return args
Thomas Heller2fadaa22008-06-16 19:56:33 +00001744 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001745 >>> GetWindowRect.errcheck = errcheck
1746 >>>
1747
1748If the :attr:`errcheck` function returns the argument tuple it receives
1749unchanged, ``ctypes`` continues the normal processing it does on the output
1750parameters. If you want to return a tuple of window coordinates instead of a
1751``RECT`` instance, you can retrieve the fields in the function and return them
1752instead, the normal processing will no longer take place::
1753
1754 >>> def errcheck(result, func, args):
1755 ... if not result:
1756 ... raise WinError()
1757 ... rc = args[1]
1758 ... return rc.left, rc.top, rc.bottom, rc.right
Thomas Heller2fadaa22008-06-16 19:56:33 +00001759 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001760 >>> GetWindowRect.errcheck = errcheck
1761 >>>
1762
1763
1764.. _ctypes-utility-functions:
1765
1766Utility functions
1767^^^^^^^^^^^^^^^^^
1768
1769
1770.. function:: addressof(obj)
1771
1772 Returns the address of the memory buffer as integer. ``obj`` must be an
1773 instance of a ctypes type.
1774
1775
1776.. function:: alignment(obj_or_type)
1777
1778 Returns the alignment requirements of a ctypes type. ``obj_or_type`` must be a
1779 ctypes type or instance.
1780
1781
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001782.. function:: byref(obj[, offset])
Georg Brandl116aa622007-08-15 14:28:22 +00001783
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001784 Returns a light-weight pointer to ``obj``, which must be an
Georg Brandl2ee470f2008-07-16 12:55:28 +00001785 instance of a ctypes type. ``offset`` defaults to zero, and must be
1786 an integer that will be added to the internal pointer value.
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001787
1788 ``byref(obj, offset)`` corresponds to this C code::
1789
1790 (((char *)&obj) + offset)
1791
1792 The returned object can only be used as a foreign function call
1793 parameter. It behaves similar to ``pointer(obj)``, but the
1794 construction is a lot faster.
Georg Brandl116aa622007-08-15 14:28:22 +00001795
1796
1797.. function:: cast(obj, type)
1798
1799 This function is similar to the cast operator in C. It returns a new instance of
1800 ``type`` which points to the same memory block as ``obj``. ``type`` must be a
1801 pointer type, and ``obj`` must be an object that can be interpreted as a
1802 pointer.
1803
1804
1805.. function:: create_string_buffer(init_or_size[, size])
1806
1807 This function creates a mutable character buffer. The returned object is a
1808 ctypes array of :class:`c_char`.
1809
1810 ``init_or_size`` must be an integer which specifies the size of the array, or a
1811 string which will be used to initialize the array items.
1812
1813 If a string is specified as first argument, the buffer is made one item larger
1814 than the length of the string so that the last element in the array is a NUL
1815 termination character. An integer can be passed as second argument which allows
1816 to specify the size of the array if the length of the string should not be used.
1817
1818 If the first parameter is a unicode string, it is converted into an 8-bit string
1819 according to ctypes conversion rules.
1820
1821
1822.. function:: create_unicode_buffer(init_or_size[, size])
1823
1824 This function creates a mutable unicode character buffer. The returned object is
1825 a ctypes array of :class:`c_wchar`.
1826
1827 ``init_or_size`` must be an integer which specifies the size of the array, or a
1828 unicode string which will be used to initialize the array items.
1829
1830 If a unicode string is specified as first argument, the buffer is made one item
1831 larger than the length of the string so that the last element in the array is a
1832 NUL termination character. An integer can be passed as second argument which
1833 allows to specify the size of the array if the length of the string should not
1834 be used.
1835
1836 If the first parameter is a 8-bit string, it is converted into an unicode string
1837 according to ctypes conversion rules.
1838
1839
1840.. function:: DllCanUnloadNow()
1841
Thomas Woutersed03b412007-08-28 21:37:11 +00001842 Windows only: This function is a hook which allows to implement in-process COM
Georg Brandl116aa622007-08-15 14:28:22 +00001843 servers with ctypes. It is called from the DllCanUnloadNow function that the
1844 _ctypes extension dll exports.
1845
1846
1847.. function:: DllGetClassObject()
1848
Thomas Woutersed03b412007-08-28 21:37:11 +00001849 Windows only: This function is a hook which allows to implement in-process COM
Georg Brandl116aa622007-08-15 14:28:22 +00001850 servers with ctypes. It is called from the DllGetClassObject function that the
1851 ``_ctypes`` extension dll exports.
1852
Thomas Heller2fadaa22008-06-16 19:56:33 +00001853.. function:: find_library(name)
1854 :module: ctypes.util
1855
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001856 Try to find a library and return a pathname. *name* is the library name
Benjamin Peterson28d88b42009-01-09 03:03:23 +00001857 without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001858 number (this is the form used for the posix linker option :option:`-l`). If
1859 no library can be found, returns ``None``.
Thomas Heller2fadaa22008-06-16 19:56:33 +00001860
1861 The exact functionality is system dependent.
1862
Thomas Heller2fadaa22008-06-16 19:56:33 +00001863
1864.. function:: find_msvcrt()
1865 :module: ctypes.util
1866
1867 Windows only: return the filename of the VC runtype library used
1868 by Python, and by the extension modules. If the name of the
1869 library cannot be determined, ``None`` is returned.
1870
1871 If you need to free memory, for example, allocated by an extension
1872 module with a call to the ``free(void *)``, it is important that you
1873 use the function in the same library that allocated the memory.
1874
Georg Brandl116aa622007-08-15 14:28:22 +00001875.. function:: FormatError([code])
1876
1877 Windows only: Returns a textual description of the error code. If no error code
1878 is specified, the last error code is used by calling the Windows api function
1879 GetLastError.
1880
1881
1882.. function:: GetLastError()
1883
1884 Windows only: Returns the last error code set by Windows in the calling thread.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001885 This function calls the Windows `GetLastError()` function directly,
1886 it does not return the ctypes-private copy of the error code.
Georg Brandl116aa622007-08-15 14:28:22 +00001887
Thomas Hellerb795f5282008-06-10 15:26:58 +00001888.. function:: get_errno()
1889
1890 Returns the current value of the ctypes-private copy of the system
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001891 :data:`errno` variable in the calling thread.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001892
Thomas Hellerb795f5282008-06-10 15:26:58 +00001893.. function:: get_last_error()
1894
1895 Windows only: returns the current value of the ctypes-private copy of the system
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001896 :data:`LastError` variable in the calling thread.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001897
Georg Brandl116aa622007-08-15 14:28:22 +00001898.. function:: memmove(dst, src, count)
1899
1900 Same as the standard C memmove library function: copies *count* bytes from
1901 ``src`` to *dst*. *dst* and ``src`` must be integers or ctypes instances that
1902 can be converted to pointers.
1903
1904
1905.. function:: memset(dst, c, count)
1906
1907 Same as the standard C memset library function: fills the memory block at
1908 address *dst* with *count* bytes of value *c*. *dst* must be an integer
1909 specifying an address, or a ctypes instance.
1910
1911
1912.. function:: POINTER(type)
1913
1914 This factory function creates and returns a new ctypes pointer type. Pointer
1915 types are cached an reused internally, so calling this function repeatedly is
1916 cheap. type must be a ctypes type.
1917
1918
1919.. function:: pointer(obj)
1920
1921 This function creates a new pointer instance, pointing to ``obj``. The returned
1922 object is of the type POINTER(type(obj)).
1923
1924 Note: If you just want to pass a pointer to an object to a foreign function
1925 call, you should use ``byref(obj)`` which is much faster.
1926
1927
1928.. function:: resize(obj, size)
1929
1930 This function resizes the internal memory buffer of obj, which must be an
1931 instance of a ctypes type. It is not possible to make the buffer smaller than
1932 the native size of the objects type, as given by sizeof(type(obj)), but it is
1933 possible to enlarge the buffer.
1934
1935
1936.. function:: set_conversion_mode(encoding, errors)
1937
1938 This function sets the rules that ctypes objects use when converting between
1939 8-bit strings and unicode strings. encoding must be a string specifying an
1940 encoding, like ``'utf-8'`` or ``'mbcs'``, errors must be a string specifying the
1941 error handling on encoding/decoding errors. Examples of possible values are
1942 ``"strict"``, ``"replace"``, or ``"ignore"``.
1943
1944 ``set_conversion_mode`` returns a 2-tuple containing the previous conversion
1945 rules. On windows, the initial conversion rules are ``('mbcs', 'ignore')``, on
1946 other systems ``('ascii', 'strict')``.
1947
1948
Thomas Hellerb795f5282008-06-10 15:26:58 +00001949.. function:: set_errno(value)
1950
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001951 Set the current value of the ctypes-private copy of the system :data:`errno`
1952 variable in the calling thread to *value* and return the previous value.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001953
Thomas Hellerb795f5282008-06-10 15:26:58 +00001954.. function:: set_last_error(value)
1955
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001956 Windows only: set the current value of the ctypes-private copy of the system
1957 :data:`LastError` variable in the calling thread to *value* and return the
1958 previous value.
Thomas Hellerb795f5282008-06-10 15:26:58 +00001959
Georg Brandl116aa622007-08-15 14:28:22 +00001960.. function:: sizeof(obj_or_type)
1961
1962 Returns the size in bytes of a ctypes type or instance memory buffer. Does the
1963 same as the C ``sizeof()`` function.
1964
1965
1966.. function:: string_at(address[, size])
1967
1968 This function returns the string starting at memory address address. If size
1969 is specified, it is used as size, otherwise the string is assumed to be
1970 zero-terminated.
1971
1972
1973.. function:: WinError(code=None, descr=None)
1974
1975 Windows only: this function is probably the worst-named thing in ctypes. It
1976 creates an instance of WindowsError. If *code* is not specified,
1977 ``GetLastError`` is called to determine the error code. If ``descr`` is not
Thomas Woutersed03b412007-08-28 21:37:11 +00001978 specified, :func:`FormatError` is called to get a textual description of the
Georg Brandl116aa622007-08-15 14:28:22 +00001979 error.
1980
1981
1982.. function:: wstring_at(address)
1983
1984 This function returns the wide character string starting at memory address
1985 ``address`` as unicode string. If ``size`` is specified, it is used as the
1986 number of characters of the string, otherwise the string is assumed to be
1987 zero-terminated.
1988
1989
1990.. _ctypes-data-types:
1991
1992Data types
1993^^^^^^^^^^
1994
1995
1996.. class:: _CData
1997
1998 This non-public class is the common base class of all ctypes data types. Among
1999 other things, all ctypes type instances contain a memory block that hold C
2000 compatible data; the address of the memory block is returned by the
2001 ``addressof()`` helper function. Another instance variable is exposed as
2002 :attr:`_objects`; this contains other Python objects that need to be kept alive
2003 in case the memory block contains pointers.
2004
Benjamin Petersone41251e2008-04-25 01:59:09 +00002005 Common methods of ctypes data types, these are all class methods (to be
2006 exact, they are methods of the :term:`metaclass`):
Georg Brandl116aa622007-08-15 14:28:22 +00002007
2008
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002009 .. method:: _CData.from_buffer(source[, offset])
2010
2011 This method returns a ctypes instance that shares the buffer of
2012 the ``source`` object. The ``source`` object must support the
2013 writeable buffer interface. The optional ``offset`` parameter
2014 specifies an offset into the source buffer in bytes; the default
2015 is zero. If the source buffer is not large enough a ValueError
2016 is raised.
2017
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002018
2019 .. method:: _CData.from_buffer_copy(source[, offset])
2020
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002021 This method creates a ctypes instance, copying the buffer from
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002022 the source object buffer which must be readable. The optional
2023 ``offset`` parameter specifies an offset into the source buffer
2024 in bytes; the default is zero. If the source buffer is not
2025 large enough a ValueError is raised.
2026
Christian Heimes81ee3ef2008-05-04 22:42:01 +00002027
Benjamin Petersone41251e2008-04-25 01:59:09 +00002028 .. method:: from_address(address)
Georg Brandl116aa622007-08-15 14:28:22 +00002029
Benjamin Petersone41251e2008-04-25 01:59:09 +00002030 This method returns a ctypes type instance using the memory specified by
2031 address which must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +00002032
2033
Benjamin Petersone41251e2008-04-25 01:59:09 +00002034 .. method:: from_param(obj)
Georg Brandl116aa622007-08-15 14:28:22 +00002035
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002036 This method adapts *obj* to a ctypes type. It is called with the actual
2037 object used in a foreign function call when the type is present in the
2038 foreign function's :attr:`argtypes` tuple; it must return an object that
2039 can be used as a function call parameter.
Georg Brandl116aa622007-08-15 14:28:22 +00002040
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002041 All ctypes data types have a default implementation of this classmethod
2042 that normally returns ``obj`` if that is an instance of the type. Some
Benjamin Petersone41251e2008-04-25 01:59:09 +00002043 types accept other objects as well.
Georg Brandl116aa622007-08-15 14:28:22 +00002044
2045
Benjamin Petersone41251e2008-04-25 01:59:09 +00002046 .. method:: in_dll(library, name)
Georg Brandl116aa622007-08-15 14:28:22 +00002047
Benjamin Petersone41251e2008-04-25 01:59:09 +00002048 This method returns a ctypes type instance exported by a shared
2049 library. *name* is the name of the symbol that exports the data, *library*
2050 is the loaded shared library.
Georg Brandl116aa622007-08-15 14:28:22 +00002051
2052
Benjamin Petersone41251e2008-04-25 01:59:09 +00002053 Common instance variables of ctypes data types:
Georg Brandl116aa622007-08-15 14:28:22 +00002054
2055
Benjamin Petersone41251e2008-04-25 01:59:09 +00002056 .. attribute:: _b_base_
Georg Brandl116aa622007-08-15 14:28:22 +00002057
Benjamin Petersone41251e2008-04-25 01:59:09 +00002058 Sometimes ctypes data instances do not own the memory block they contain,
2059 instead they share part of the memory block of a base object. The
2060 :attr:`_b_base_` read-only member is the root ctypes object that owns the
2061 memory block.
Georg Brandl116aa622007-08-15 14:28:22 +00002062
2063
Benjamin Petersone41251e2008-04-25 01:59:09 +00002064 .. attribute:: _b_needsfree_
Georg Brandl116aa622007-08-15 14:28:22 +00002065
Benjamin Petersone41251e2008-04-25 01:59:09 +00002066 This read-only variable is true when the ctypes data instance has
2067 allocated the memory block itself, false otherwise.
2068
2069
2070 .. attribute:: _objects
2071
2072 This member is either ``None`` or a dictionary containing Python objects
2073 that need to be kept alive so that the memory block contents is kept
2074 valid. This object is only exposed for debugging; never modify the
2075 contents of this dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00002076
2077
2078.. _ctypes-fundamental-data-types-2:
2079
2080Fundamental data types
2081^^^^^^^^^^^^^^^^^^^^^^
2082
2083
2084.. class:: _SimpleCData
2085
Benjamin Peterson35e8c462008-04-24 02:34:53 +00002086 This non-public class is the base class of all fundamental ctypes data
2087 types. It is mentioned here because it contains the common attributes of the
2088 fundamental ctypes data types. ``_SimpleCData`` is a subclass of ``_CData``,
2089 so it inherits their methods and attributes. ctypes data types that are not
2090 and do not contain pointers can now be pickled.
Thomas Heller13394e92008-02-13 20:40:44 +00002091
Benjamin Petersone41251e2008-04-25 01:59:09 +00002092 Instances have a single attribute:
Georg Brandl116aa622007-08-15 14:28:22 +00002093
2094
Benjamin Petersone41251e2008-04-25 01:59:09 +00002095 .. attribute:: value
Georg Brandl116aa622007-08-15 14:28:22 +00002096
Benjamin Petersone41251e2008-04-25 01:59:09 +00002097 This attribute contains the actual value of the instance. For integer and
2098 pointer types, it is an integer, for character types, it is a single
2099 character string, for character pointer types it is a Python string or
2100 unicode string.
Georg Brandl116aa622007-08-15 14:28:22 +00002101
Benjamin Petersone41251e2008-04-25 01:59:09 +00002102 When the ``value`` attribute is retrieved from a ctypes instance, usually
2103 a new object is returned each time. ``ctypes`` does *not* implement
2104 original object return, always a new object is constructed. The same is
2105 true for all other ctypes object instances.
Georg Brandl116aa622007-08-15 14:28:22 +00002106
2107Fundamental data types, when returned as foreign function call results, or, for
2108example, by retrieving structure field members or array items, are transparently
2109converted to native Python types. In other words, if a foreign function has a
2110:attr:`restype` of :class:`c_char_p`, you will always receive a Python string,
2111*not* a :class:`c_char_p` instance.
2112
Thomas Woutersed03b412007-08-28 21:37:11 +00002113Subclasses of fundamental data types do *not* inherit this behavior. So, if a
Georg Brandl116aa622007-08-15 14:28:22 +00002114foreign functions :attr:`restype` is a subclass of :class:`c_void_p`, you will
2115receive an instance of this subclass from the function call. Of course, you can
2116get the value of the pointer by accessing the ``value`` attribute.
2117
2118These are the fundamental ctypes data types:
2119
2120
2121.. class:: c_byte
2122
2123 Represents the C signed char datatype, and interprets the value as small
2124 integer. The constructor accepts an optional integer initializer; no overflow
2125 checking is done.
2126
2127
2128.. class:: c_char
2129
2130 Represents the C char datatype, and interprets the value as a single character.
2131 The constructor accepts an optional string initializer, the length of the string
2132 must be exactly one character.
2133
2134
2135.. class:: c_char_p
2136
2137 Represents the C char \* datatype, which must be a pointer to a zero-terminated
2138 string. The constructor accepts an integer address, or a string.
2139
2140
2141.. class:: c_double
2142
2143 Represents the C double datatype. The constructor accepts an optional float
2144 initializer.
2145
2146
Thomas Wouters89d996e2007-09-08 17:39:28 +00002147.. class:: c_longdouble
2148
2149 Represents the C long double datatype. The constructor accepts an
2150 optional float initializer. On platforms where ``sizeof(long
2151 double) == sizeof(double)`` it is an alias to :class:`c_double`.
2152
Georg Brandl116aa622007-08-15 14:28:22 +00002153.. class:: c_float
2154
Thomas Wouters89d996e2007-09-08 17:39:28 +00002155 Represents the C float datatype. The constructor accepts an optional float
Georg Brandl116aa622007-08-15 14:28:22 +00002156 initializer.
2157
2158
2159.. class:: c_int
2160
2161 Represents the C signed int datatype. The constructor accepts an optional
2162 integer initializer; no overflow checking is done. On platforms where
2163 ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`.
2164
2165
2166.. class:: c_int8
2167
2168 Represents the C 8-bit ``signed int`` datatype. Usually an alias for
2169 :class:`c_byte`.
2170
2171
2172.. class:: c_int16
2173
2174 Represents the C 16-bit signed int datatype. Usually an alias for
2175 :class:`c_short`.
2176
2177
2178.. class:: c_int32
2179
2180 Represents the C 32-bit signed int datatype. Usually an alias for
2181 :class:`c_int`.
2182
2183
2184.. class:: c_int64
2185
2186 Represents the C 64-bit ``signed int`` datatype. Usually an alias for
2187 :class:`c_longlong`.
2188
2189
2190.. class:: c_long
2191
2192 Represents the C ``signed long`` datatype. The constructor accepts an optional
2193 integer initializer; no overflow checking is done.
2194
2195
2196.. class:: c_longlong
2197
2198 Represents the C ``signed long long`` datatype. The constructor accepts an
2199 optional integer initializer; no overflow checking is done.
2200
2201
2202.. class:: c_short
2203
2204 Represents the C ``signed short`` datatype. The constructor accepts an optional
2205 integer initializer; no overflow checking is done.
2206
2207
2208.. class:: c_size_t
2209
2210 Represents the C ``size_t`` datatype.
2211
2212
2213.. class:: c_ubyte
2214
2215 Represents the C ``unsigned char`` datatype, it interprets the value as small
2216 integer. The constructor accepts an optional integer initializer; no overflow
2217 checking is done.
2218
2219
2220.. class:: c_uint
2221
2222 Represents the C ``unsigned int`` datatype. The constructor accepts an optional
2223 integer initializer; no overflow checking is done. On platforms where
2224 ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`.
2225
2226
2227.. class:: c_uint8
2228
2229 Represents the C 8-bit unsigned int datatype. Usually an alias for
2230 :class:`c_ubyte`.
2231
2232
2233.. class:: c_uint16
2234
2235 Represents the C 16-bit unsigned int datatype. Usually an alias for
2236 :class:`c_ushort`.
2237
2238
2239.. class:: c_uint32
2240
2241 Represents the C 32-bit unsigned int datatype. Usually an alias for
2242 :class:`c_uint`.
2243
2244
2245.. class:: c_uint64
2246
2247 Represents the C 64-bit unsigned int datatype. Usually an alias for
2248 :class:`c_ulonglong`.
2249
2250
2251.. class:: c_ulong
2252
2253 Represents the C ``unsigned long`` datatype. The constructor accepts an optional
2254 integer initializer; no overflow checking is done.
2255
2256
2257.. class:: c_ulonglong
2258
2259 Represents the C ``unsigned long long`` datatype. The constructor accepts an
2260 optional integer initializer; no overflow checking is done.
2261
2262
2263.. class:: c_ushort
2264
2265 Represents the C ``unsigned short`` datatype. The constructor accepts an
2266 optional integer initializer; no overflow checking is done.
2267
2268
2269.. class:: c_void_p
2270
2271 Represents the C ``void *`` type. The value is represented as integer. The
2272 constructor accepts an optional integer initializer.
2273
2274
2275.. class:: c_wchar
2276
2277 Represents the C ``wchar_t`` datatype, and interprets the value as a single
2278 character unicode string. The constructor accepts an optional string
2279 initializer, the length of the string must be exactly one character.
2280
2281
2282.. class:: c_wchar_p
2283
2284 Represents the C ``wchar_t *`` datatype, which must be a pointer to a
2285 zero-terminated wide character string. The constructor accepts an integer
2286 address, or a string.
2287
2288
2289.. class:: c_bool
2290
2291 Represent the C ``bool`` datatype (more accurately, _Bool from C99). Its value
2292 can be True or False, and the constructor accepts any object that has a truth
2293 value.
2294
Georg Brandl116aa622007-08-15 14:28:22 +00002295
2296.. class:: HRESULT
2297
2298 Windows only: Represents a :class:`HRESULT` value, which contains success or
2299 error information for a function or method call.
2300
2301
2302.. class:: py_object
2303
2304 Represents the C ``PyObject *`` datatype. Calling this without an argument
2305 creates a ``NULL`` ``PyObject *`` pointer.
2306
2307The ``ctypes.wintypes`` module provides quite some other Windows specific data
2308types, for example ``HWND``, ``WPARAM``, or ``DWORD``. Some useful structures
2309like ``MSG`` or ``RECT`` are also defined.
2310
2311
2312.. _ctypes-structured-data-types:
2313
2314Structured data types
2315^^^^^^^^^^^^^^^^^^^^^
2316
2317
2318.. class:: Union(*args, **kw)
2319
2320 Abstract base class for unions in native byte order.
2321
2322
2323.. class:: BigEndianStructure(*args, **kw)
2324
2325 Abstract base class for structures in *big endian* byte order.
2326
2327
2328.. class:: LittleEndianStructure(*args, **kw)
2329
2330 Abstract base class for structures in *little endian* byte order.
2331
2332Structures with non-native byte order cannot contain pointer type fields, or any
2333other data types containing pointer type fields.
2334
2335
2336.. class:: Structure(*args, **kw)
2337
2338 Abstract base class for structures in *native* byte order.
2339
Benjamin Petersone41251e2008-04-25 01:59:09 +00002340 Concrete structure and union types must be created by subclassing one of these
2341 types, and at least define a :attr:`_fields_` class variable. ``ctypes`` will
2342 create :term:`descriptor`\s which allow reading and writing the fields by direct
2343 attribute accesses. These are the
Georg Brandl116aa622007-08-15 14:28:22 +00002344
2345
Benjamin Petersone41251e2008-04-25 01:59:09 +00002346 .. attribute:: _fields_
Georg Brandl116aa622007-08-15 14:28:22 +00002347
Benjamin Petersone41251e2008-04-25 01:59:09 +00002348 A sequence defining the structure fields. The items must be 2-tuples or
2349 3-tuples. The first item is the name of the field, the second item
2350 specifies the type of the field; it can be any ctypes data type.
Georg Brandl116aa622007-08-15 14:28:22 +00002351
Benjamin Petersone41251e2008-04-25 01:59:09 +00002352 For integer type fields like :class:`c_int`, a third optional item can be
2353 given. It must be a small positive integer defining the bit width of the
2354 field.
Georg Brandl116aa622007-08-15 14:28:22 +00002355
Benjamin Petersone41251e2008-04-25 01:59:09 +00002356 Field names must be unique within one structure or union. This is not
2357 checked, only one field can be accessed when names are repeated.
Georg Brandl116aa622007-08-15 14:28:22 +00002358
Benjamin Petersone41251e2008-04-25 01:59:09 +00002359 It is possible to define the :attr:`_fields_` class variable *after* the
2360 class statement that defines the Structure subclass, this allows to create
2361 data types that directly or indirectly reference themselves::
Georg Brandl116aa622007-08-15 14:28:22 +00002362
Benjamin Petersone41251e2008-04-25 01:59:09 +00002363 class List(Structure):
2364 pass
2365 List._fields_ = [("pnext", POINTER(List)),
2366 ...
2367 ]
Georg Brandl116aa622007-08-15 14:28:22 +00002368
Benjamin Petersone41251e2008-04-25 01:59:09 +00002369 The :attr:`_fields_` class variable must, however, be defined before the
2370 type is first used (an instance is created, ``sizeof()`` is called on it,
2371 and so on). Later assignments to the :attr:`_fields_` class variable will
2372 raise an AttributeError.
Georg Brandl116aa622007-08-15 14:28:22 +00002373
Benjamin Petersone41251e2008-04-25 01:59:09 +00002374 Structure and union subclass constructors accept both positional and named
2375 arguments. Positional arguments are used to initialize the fields in the
2376 same order as they appear in the :attr:`_fields_` definition, named
2377 arguments are used to initialize the fields with the corresponding name.
Georg Brandl116aa622007-08-15 14:28:22 +00002378
Benjamin Petersone41251e2008-04-25 01:59:09 +00002379 It is possible to defined sub-subclasses of structure types, they inherit
2380 the fields of the base class plus the :attr:`_fields_` defined in the
2381 sub-subclass, if any.
Georg Brandl116aa622007-08-15 14:28:22 +00002382
2383
Benjamin Petersone41251e2008-04-25 01:59:09 +00002384 .. attribute:: _pack_
Georg Brandl116aa622007-08-15 14:28:22 +00002385
Benjamin Petersone41251e2008-04-25 01:59:09 +00002386 An optional small integer that allows to override the alignment of
2387 structure fields in the instance. :attr:`_pack_` must already be defined
2388 when :attr:`_fields_` is assigned, otherwise it will have no effect.
Georg Brandl116aa622007-08-15 14:28:22 +00002389
2390
Benjamin Petersone41251e2008-04-25 01:59:09 +00002391 .. attribute:: _anonymous_
Georg Brandl116aa622007-08-15 14:28:22 +00002392
Benjamin Petersone41251e2008-04-25 01:59:09 +00002393 An optional sequence that lists the names of unnamed (anonymous) fields.
2394 ``_anonymous_`` must be already defined when :attr:`_fields_` is assigned,
2395 otherwise it will have no effect.
Georg Brandl116aa622007-08-15 14:28:22 +00002396
Benjamin Petersone41251e2008-04-25 01:59:09 +00002397 The fields listed in this variable must be structure or union type fields.
2398 ``ctypes`` will create descriptors in the structure type that allows to
2399 access the nested fields directly, without the need to create the
2400 structure or union field.
Georg Brandl116aa622007-08-15 14:28:22 +00002401
Benjamin Petersone41251e2008-04-25 01:59:09 +00002402 Here is an example type (Windows)::
Georg Brandl116aa622007-08-15 14:28:22 +00002403
Benjamin Petersone41251e2008-04-25 01:59:09 +00002404 class _U(Union):
2405 _fields_ = [("lptdesc", POINTER(TYPEDESC)),
2406 ("lpadesc", POINTER(ARRAYDESC)),
2407 ("hreftype", HREFTYPE)]
Georg Brandl116aa622007-08-15 14:28:22 +00002408
Benjamin Petersone41251e2008-04-25 01:59:09 +00002409 class TYPEDESC(Structure):
Benjamin Petersonb58dda72009-01-18 22:27:04 +00002410 _anonymous_ = ("u",)
Benjamin Petersone41251e2008-04-25 01:59:09 +00002411 _fields_ = [("u", _U),
2412 ("vt", VARTYPE)]
Georg Brandl116aa622007-08-15 14:28:22 +00002413
Georg Brandl116aa622007-08-15 14:28:22 +00002414
Benjamin Petersone41251e2008-04-25 01:59:09 +00002415 The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field
2416 specifies which one of the union fields is valid. Since the ``u`` field
2417 is defined as anonymous field, it is now possible to access the members
2418 directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc``
2419 are equivalent, but the former is faster since it does not need to create
2420 a temporary union instance::
Georg Brandl116aa622007-08-15 14:28:22 +00002421
Benjamin Petersone41251e2008-04-25 01:59:09 +00002422 td = TYPEDESC()
2423 td.vt = VT_PTR
2424 td.lptdesc = POINTER(some_type)
2425 td.u.lptdesc = POINTER(some_type)
Georg Brandl116aa622007-08-15 14:28:22 +00002426
2427It is possible to defined sub-subclasses of structures, they inherit the fields
2428of the base class. If the subclass definition has a separate :attr:`_fields_`
2429variable, the fields specified in this are appended to the fields of the base
2430class.
2431
2432Structure and union constructors accept both positional and keyword arguments.
2433Positional arguments are used to initialize member fields in the same order as
2434they are appear in :attr:`_fields_`. Keyword arguments in the constructor are
2435interpreted as attribute assignments, so they will initialize :attr:`_fields_`
2436with the same name, or create new attributes for names not present in
2437:attr:`_fields_`.
2438
2439
2440.. _ctypes-arrays-pointers:
2441
2442Arrays and pointers
2443^^^^^^^^^^^^^^^^^^^
2444
2445Not yet written - please see the sections :ref:`ctypes-pointers` and
2446section :ref:`ctypes-arrays` in the tutorial.
2447