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