| 1 |
:mod:`ctypes` --- A foreign function library for Python |
| 2 |
======================================================= |
| 3 |
|
| 4 |
.. module:: ctypes |
| 5 |
:synopsis: A foreign function library for Python. |
| 6 |
.. moduleauthor:: Thomas Heller <[email protected]> |
| 7 |
|
| 8 |
|
| 9 |
.. versionadded:: 2.5 |
| 10 |
|
| 11 |
:mod:`ctypes` is a foreign function library for Python. It provides C compatible |
| 12 |
data types, and allows calling functions in DLLs or shared libraries. It can be |
| 13 |
used to wrap these libraries in pure Python. |
| 14 |
|
| 15 |
|
| 16 |
.. _ctypes-ctypes-tutorial: |
| 17 |
|
| 18 |
ctypes tutorial |
| 19 |
--------------- |
| 20 |
|
| 21 |
Note: The code samples in this tutorial use :mod:`doctest` to make sure that |
| 22 |
they actually work. Since some code samples behave differently under Linux, |
| 23 |
Windows, or Mac OS X, they contain doctest directives in comments. |
| 24 |
|
| 25 |
Note: Some code samples reference the ctypes :class:`c_int` type. This type is |
| 26 |
an alias for the :class:`c_long` type on 32-bit systems. So, you should not be |
| 27 |
confused if :class:`c_long` is printed if you would expect :class:`c_int` --- |
| 28 |
they are actually the same type. |
| 29 |
|
| 30 |
|
| 31 |
.. _ctypes-loading-dynamic-link-libraries: |
| 32 |
|
| 33 |
Loading dynamic link libraries |
| 34 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 35 |
|
| 36 |
:mod:`ctypes` exports the *cdll*, and on Windows *windll* and *oledll* |
| 37 |
objects, for loading dynamic link libraries. |
| 38 |
|
| 39 |
You load libraries by accessing them as attributes of these objects. *cdll* |
| 40 |
loads libraries which export functions using the standard ``cdecl`` calling |
| 41 |
convention, while *windll* libraries call functions using the ``stdcall`` |
| 42 |
calling convention. *oledll* also uses the ``stdcall`` calling convention, and |
| 43 |
assumes the functions return a Windows :c:type:`HRESULT` error code. The error |
| 44 |
code is used to automatically raise a :class:`WindowsError` exception when the |
| 45 |
function call fails. |
| 46 |
|
| 47 |
Here are some examples for Windows. Note that ``msvcrt`` is the MS standard C |
| 48 |
library containing most standard C functions, and uses the cdecl calling |
| 49 |
convention:: |
| 50 |
|
| 51 |
>>> from ctypes import * |
| 52 |
>>> print windll.kernel32 # doctest: +WINDOWS |
| 53 |
<WinDLL 'kernel32', handle ... at ...> |
| 54 |
>>> print cdll.msvcrt # doctest: +WINDOWS |
| 55 |
<CDLL 'msvcrt', handle ... at ...> |
| 56 |
>>> libc = cdll.msvcrt # doctest: +WINDOWS |
| 57 |
>>> |
| 58 |
|
| 59 |
Windows appends the usual ``.dll`` file suffix automatically. |
| 60 |
|
| 61 |
On Linux, it is required to specify the filename *including* the extension to |
| 62 |
load a library, so attribute access can not be used to load libraries. Either the |
| 63 |
:meth:`LoadLibrary` method of the dll loaders should be used, or you should load |
| 64 |
the library by creating an instance of CDLL by calling the constructor:: |
| 65 |
|
| 66 |
>>> cdll.LoadLibrary("libc.so.6") # doctest: +LINUX |
| 67 |
<CDLL 'libc.so.6', handle ... at ...> |
| 68 |
>>> libc = CDLL("libc.so.6") # doctest: +LINUX |
| 69 |
>>> libc # doctest: +LINUX |
| 70 |
<CDLL 'libc.so.6', handle ... at ...> |
| 71 |
>>> |
| 72 |
|
| 73 |
.. XXX Add section for Mac OS X. |
| 74 |
|
| 75 |
|
| 76 |
.. _ctypes-accessing-functions-from-loaded-dlls: |
| 77 |
|
| 78 |
Accessing functions from loaded dlls |
| 79 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 80 |
|
| 81 |
Functions are accessed as attributes of dll objects:: |
| 82 |
|
| 83 |
>>> from ctypes import * |
| 84 |
>>> libc.printf |
| 85 |
<_FuncPtr object at 0x...> |
| 86 |
>>> print windll.kernel32.GetModuleHandleA # doctest: +WINDOWS |
| 87 |
<_FuncPtr object at 0x...> |
| 88 |
>>> print windll.kernel32.MyOwnFunction # doctest: +WINDOWS |
| 89 |
Traceback (most recent call last): |
| 90 |
File "<stdin>", line 1, in <module> |
| 91 |
File "ctypes.py", line 239, in __getattr__ |
| 92 |
func = _StdcallFuncPtr(name, self) |
| 93 |
AttributeError: function 'MyOwnFunction' not found |
| 94 |
>>> |
| 95 |
|
| 96 |
Note that win32 system dlls like ``kernel32`` and ``user32`` often export ANSI |
| 97 |
as well as UNICODE versions of a function. The UNICODE version is exported with |
| 98 |
an ``W`` appended to the name, while the ANSI version is exported with an ``A`` |
| 99 |
appended to the name. The win32 ``GetModuleHandle`` function, which returns a |
| 100 |
*module handle* for a given module name, has the following C prototype, and a |
| 101 |
macro is used to expose one of them as ``GetModuleHandle`` depending on whether |
| 102 |
UNICODE is defined or not:: |
| 103 |
|
| 104 |
/* ANSI version */ |
| 105 |
HMODULE GetModuleHandleA(LPCSTR lpModuleName); |
| 106 |
/* UNICODE version */ |
| 107 |
HMODULE GetModuleHandleW(LPCWSTR lpModuleName); |
| 108 |
|
| 109 |
*windll* does not try to select one of them by magic, you must access the |
| 110 |
version you need by specifying ``GetModuleHandleA`` or ``GetModuleHandleW`` |
| 111 |
explicitly, and then call it with strings or unicode strings |
| 112 |
respectively. |
| 113 |
|
| 114 |
Sometimes, dlls export functions with names which aren't valid Python |
| 115 |
identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use |
| 116 |
:func:`getattr` to retrieve the function:: |
| 117 |
|
| 118 |
>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") # doctest: +WINDOWS |
| 119 |
<_FuncPtr object at 0x...> |
| 120 |
>>> |
| 121 |
|
| 122 |
On Windows, some dlls export functions not by name but by ordinal. These |
| 123 |
functions can be accessed by indexing the dll object with the ordinal number:: |
| 124 |
|
| 125 |
>>> cdll.kernel32[1] # doctest: +WINDOWS |
| 126 |
<_FuncPtr object at 0x...> |
| 127 |
>>> cdll.kernel32[0] # doctest: +WINDOWS |
| 128 |
Traceback (most recent call last): |
| 129 |
File "<stdin>", line 1, in <module> |
| 130 |
File "ctypes.py", line 310, in __getitem__ |
| 131 |
func = _StdcallFuncPtr(name, self) |
| 132 |
AttributeError: function ordinal 0 not found |
| 133 |
>>> |
| 134 |
|
| 135 |
|
| 136 |
.. _ctypes-calling-functions: |
| 137 |
|
| 138 |
Calling functions |
| 139 |
^^^^^^^^^^^^^^^^^ |
| 140 |
|
| 141 |
You can call these functions like any other Python callable. This example uses |
| 142 |
the ``time()`` function, which returns system time in seconds since the Unix |
| 143 |
epoch, and the ``GetModuleHandleA()`` function, which returns a win32 module |
| 144 |
handle. |
| 145 |
|
| 146 |
This example calls both functions with a NULL pointer (``None`` should be used |
| 147 |
as the NULL pointer):: |
| 148 |
|
| 149 |
>>> print libc.time(None) # doctest: +SKIP |
| 150 |
1150640792 |
| 151 |
>>> print hex(windll.kernel32.GetModuleHandleA(None)) # doctest: +WINDOWS |
| 152 |
0x1d000000 |
| 153 |
>>> |
| 154 |
|
| 155 |
:mod:`ctypes` tries to protect you from calling functions with the wrong number |
| 156 |
of arguments or the wrong calling convention. Unfortunately this only works on |
| 157 |
Windows. It does this by examining the stack after the function returns, so |
| 158 |
although an error is raised the function *has* been called:: |
| 159 |
|
| 160 |
>>> windll.kernel32.GetModuleHandleA() # doctest: +WINDOWS |
| 161 |
Traceback (most recent call last): |
| 162 |
File "<stdin>", line 1, in <module> |
| 163 |
ValueError: Procedure probably called with not enough arguments (4 bytes missing) |
| 164 |
>>> windll.kernel32.GetModuleHandleA(0, 0) # doctest: +WINDOWS |
| 165 |
Traceback (most recent call last): |
| 166 |
File "<stdin>", line 1, in <module> |
| 167 |
ValueError: Procedure probably called with too many arguments (4 bytes in excess) |
| 168 |
>>> |
| 169 |
|
| 170 |
The same exception is raised when you call an ``stdcall`` function with the |
| 171 |
``cdecl`` calling convention, or vice versa:: |
| 172 |
|
| 173 |
>>> cdll.kernel32.GetModuleHandleA(None) # doctest: +WINDOWS |
| 174 |
Traceback (most recent call last): |
| 175 |
File "<stdin>", line 1, in <module> |
| 176 |
ValueError: Procedure probably called with not enough arguments (4 bytes missing) |
| 177 |
>>> |
| 178 |
|
| 179 |
>>> windll.msvcrt.printf("spam") # doctest: +WINDOWS |
| 180 |
Traceback (most recent call last): |
| 181 |
File "<stdin>", line 1, in <module> |
| 182 |
ValueError: Procedure probably called with too many arguments (4 bytes in excess) |
| 183 |
>>> |
| 184 |
|
| 185 |
To find out the correct calling convention you have to look into the C header |
| 186 |
file or the documentation for the function you want to call. |
| 187 |
|
| 188 |
On Windows, :mod:`ctypes` uses win32 structured exception handling to prevent |
| 189 |
crashes from general protection faults when functions are called with invalid |
| 190 |
argument values:: |
| 191 |
|
| 192 |
>>> windll.kernel32.GetModuleHandleA(32) # doctest: +WINDOWS |
| 193 |
Traceback (most recent call last): |
| 194 |
File "<stdin>", line 1, in <module> |
| 195 |
WindowsError: exception: access violation reading 0x00000020 |
| 196 |
>>> |
| 197 |
|
| 198 |
There are, however, enough ways to crash Python with :mod:`ctypes`, so you |
| 199 |
should be careful anyway. |
| 200 |
|
| 201 |
``None``, integers, longs, byte strings and unicode strings are the only native |
| 202 |
Python objects that can directly be used as parameters in these function calls. |
| 203 |
``None`` is passed as a C ``NULL`` pointer, byte strings and unicode strings are |
| 204 |
passed as pointer to the memory block that contains their data (:c:type:`char *` |
| 205 |
or :c:type:`wchar_t *`). Python integers and Python longs are passed as the |
| 206 |
platforms default C :c:type:`int` type, their value is masked to fit into the C |
| 207 |
type. |
| 208 |
|
| 209 |
Before we move on calling functions with other parameter types, we have to learn |
| 210 |
more about :mod:`ctypes` data types. |
| 211 |
|
| 212 |
|
| 213 |
.. _ctypes-fundamental-data-types: |
| 214 |
|
| 215 |
Fundamental data types |
| 216 |
^^^^^^^^^^^^^^^^^^^^^^ |
| 217 |
|
| 218 |
:mod:`ctypes` defines a number of primitive C compatible data types: |
| 219 |
|
| 220 |
+----------------------+------------------------------------------+----------------------------+ |
| 221 |
| ctypes type | C type | Python type | |
| 222 |
+======================+==========================================+============================+ |
| 223 |
| :class:`c_bool` | :c:type:`_Bool` | bool (1) | |
| 224 |
+----------------------+------------------------------------------+----------------------------+ |
| 225 |
| :class:`c_char` | :c:type:`char` | 1-character string | |
| 226 |
+----------------------+------------------------------------------+----------------------------+ |
| 227 |
| :class:`c_wchar` | :c:type:`wchar_t` | 1-character unicode string | |
| 228 |
+----------------------+------------------------------------------+----------------------------+ |
| 229 |
| :class:`c_byte` | :c:type:`char` | int/long | |
| 230 |
+----------------------+------------------------------------------+----------------------------+ |
| 231 |
| :class:`c_ubyte` | :c:type:`unsigned char` | int/long | |
| 232 |
+----------------------+------------------------------------------+----------------------------+ |
| 233 |
| :class:`c_short` | :c:type:`short` | int/long | |
| 234 |
+----------------------+------------------------------------------+----------------------------+ |
| 235 |
| :class:`c_ushort` | :c:type:`unsigned short` | int/long | |
| 236 |
+----------------------+------------------------------------------+----------------------------+ |
| 237 |
| :class:`c_int` | :c:type:`int` | int/long | |
| 238 |
+----------------------+------------------------------------------+----------------------------+ |
| 239 |
| :class:`c_uint` | :c:type:`unsigned int` | int/long | |
| 240 |
+----------------------+------------------------------------------+----------------------------+ |
| 241 |
| :class:`c_long` | :c:type:`long` | int/long | |
| 242 |
+----------------------+------------------------------------------+----------------------------+ |
| 243 |
| :class:`c_ulong` | :c:type:`unsigned long` | int/long | |
| 244 |
+----------------------+------------------------------------------+----------------------------+ |
| 245 |
| :class:`c_longlong` | :c:type:`__int64` or :c:type:`long long` | int/long | |
| 246 |
+----------------------+------------------------------------------+----------------------------+ |
| 247 |
| :class:`c_ulonglong` | :c:type:`unsigned __int64` or | int/long | |
| 248 |
| | :c:type:`unsigned long long` | | |
| 249 |
+----------------------+------------------------------------------+----------------------------+ |
| 250 |
| :class:`c_float` | :c:type:`float` | float | |
| 251 |
+----------------------+------------------------------------------+----------------------------+ |
| 252 |
| :class:`c_double` | :c:type:`double` | float | |
| 253 |
+----------------------+------------------------------------------+----------------------------+ |
| 254 |
| :class:`c_longdouble`| :c:type:`long double` | float | |
| 255 |
+----------------------+------------------------------------------+----------------------------+ |
| 256 |
| :class:`c_char_p` | :c:type:`char *` (NUL terminated) | string or ``None`` | |
| 257 |
+----------------------+------------------------------------------+----------------------------+ |
| 258 |
| :class:`c_wchar_p` | :c:type:`wchar_t *` (NUL terminated) | unicode or ``None`` | |
| 259 |
+----------------------+------------------------------------------+----------------------------+ |
| 260 |
| :class:`c_void_p` | :c:type:`void *` | int/long or ``None`` | |
| 261 |
+----------------------+------------------------------------------+----------------------------+ |
| 262 |
|
| 263 |
(1) |
| 264 |
The constructor accepts any object with a truth value. |
| 265 |
|
| 266 |
All these types can be created by calling them with an optional initializer of |
| 267 |
the correct type and value:: |
| 268 |
|
| 269 |
>>> c_int() |
| 270 |
c_long(0) |
| 271 |
>>> c_char_p("Hello, World") |
| 272 |
c_char_p('Hello, World') |
| 273 |
>>> c_ushort(-3) |
| 274 |
c_ushort(65533) |
| 275 |
>>> |
| 276 |
|
| 277 |
Since these types are mutable, their value can also be changed afterwards:: |
| 278 |
|
| 279 |
>>> i = c_int(42) |
| 280 |
>>> print i |
| 281 |
c_long(42) |
| 282 |
>>> print i.value |
| 283 |
42 |
| 284 |
>>> i.value = -99 |
| 285 |
>>> print i.value |
| 286 |
-99 |
| 287 |
>>> |
| 288 |
|
| 289 |
Assigning a new value to instances of the pointer types :class:`c_char_p`, |
| 290 |
:class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they |
| 291 |
point to, *not the contents* of the memory block (of course not, because Python |
| 292 |
strings are immutable):: |
| 293 |
|
| 294 |
>>> s = "Hello, World" |
| 295 |
>>> c_s = c_char_p(s) |
| 296 |
>>> print c_s |
| 297 |
c_char_p('Hello, World') |
| 298 |
>>> c_s.value = "Hi, there" |
| 299 |
>>> print c_s |
| 300 |
c_char_p('Hi, there') |
| 301 |
>>> print s # first string is unchanged |
| 302 |
Hello, World |
| 303 |
>>> |
| 304 |
|
| 305 |
You should be careful, however, not to pass them to functions expecting pointers |
| 306 |
to mutable memory. If you need mutable memory blocks, ctypes has a |
| 307 |
:func:`create_string_buffer` function which creates these in various ways. The |
| 308 |
current memory block contents can be accessed (or changed) with the ``raw`` |
| 309 |
property; if you want to access it as NUL terminated string, use the ``value`` |
| 310 |
property:: |
| 311 |
|
| 312 |
>>> from ctypes import * |
| 313 |
>>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes |
| 314 |
>>> print sizeof(p), repr(p.raw) |
| 315 |
3 '\x00\x00\x00' |
| 316 |
>>> p = create_string_buffer("Hello") # create a buffer containing a NUL terminated string |
| 317 |
>>> print sizeof(p), repr(p.raw) |
| 318 |
6 'Hello\x00' |
| 319 |
>>> print repr(p.value) |
| 320 |
'Hello' |
| 321 |
>>> p = create_string_buffer("Hello", 10) # create a 10 byte buffer |
| 322 |
>>> print sizeof(p), repr(p.raw) |
| 323 |
10 'Hello\x00\x00\x00\x00\x00' |
| 324 |
>>> p.value = "Hi" |
| 325 |
>>> print sizeof(p), repr(p.raw) |
| 326 |
10 'Hi\x00lo\x00\x00\x00\x00\x00' |
| 327 |
>>> |
| 328 |
|
| 329 |
The :func:`create_string_buffer` function replaces the :func:`c_buffer` function |
| 330 |
(which is still available as an alias), as well as the :func:`c_string` function |
| 331 |
from earlier ctypes releases. To create a mutable memory block containing |
| 332 |
unicode characters of the C type :c:type:`wchar_t` use the |
| 333 |
:func:`create_unicode_buffer` function. |
| 334 |
|
| 335 |
|
| 336 |
.. _ctypes-calling-functions-continued: |
| 337 |
|
| 338 |
Calling functions, continued |
| 339 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 340 |
|
| 341 |
Note that printf prints to the real standard output channel, *not* to |
| 342 |
:data:`sys.stdout`, so these examples will only work at the console prompt, not |
| 343 |
from within *IDLE* or *PythonWin*:: |
| 344 |
|
| 345 |
>>> printf = libc.printf |
| 346 |
>>> printf("Hello, %s\n", "World!") |
| 347 |
Hello, World! |
| 348 |
14 |
| 349 |
>>> printf("Hello, %S\n", u"World!") |
| 350 |
Hello, World! |
| 351 |
14 |
| 352 |
>>> printf("%d bottles of beer\n", 42) |
| 353 |
42 bottles of beer |
| 354 |
19 |
| 355 |
>>> printf("%f bottles of beer\n", 42.5) |
| 356 |
Traceback (most recent call last): |
| 357 |
File "<stdin>", line 1, in <module> |
| 358 |
ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2 |
| 359 |
>>> |
| 360 |
|
| 361 |
As has been mentioned before, all Python types except integers, strings, and |
| 362 |
unicode strings have to be wrapped in their corresponding :mod:`ctypes` type, so |
| 363 |
that they can be converted to the required C data type:: |
| 364 |
|
| 365 |
>>> printf("An int %d, a double %f\n", 1234, c_double(3.14)) |
| 366 |
An int 1234, a double 3.140000 |
| 367 |
31 |
| 368 |
>>> |
| 369 |
|
| 370 |
|
| 371 |
.. _ctypes-calling-functions-with-own-custom-data-types: |
| 372 |
|
| 373 |
Calling functions with your own custom data types |
| 374 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 375 |
|
| 376 |
You can also customize :mod:`ctypes` argument conversion to allow instances of |
| 377 |
your own classes be used as function arguments. :mod:`ctypes` looks for an |
| 378 |
:attr:`_as_parameter_` attribute and uses this as the function argument. Of |
| 379 |
course, it must be one of integer, string, or unicode:: |
| 380 |
|
| 381 |
>>> class Bottles(object): |
| 382 |
... def __init__(self, number): |
| 383 |
... self._as_parameter_ = number |
| 384 |
... |
| 385 |
>>> bottles = Bottles(42) |
| 386 |
>>> printf("%d bottles of beer\n", bottles) |
| 387 |
42 bottles of beer |
| 388 |
19 |
| 389 |
>>> |
| 390 |
|
| 391 |
If you don't want to store the instance's data in the :attr:`_as_parameter_` |
| 392 |
instance variable, you could define a :func:`property` which makes the data |
| 393 |
available. |
| 394 |
|
| 395 |
|
| 396 |
.. _ctypes-specifying-required-argument-types: |
| 397 |
|
| 398 |
Specifying the required argument types (function prototypes) |
| 399 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 400 |
|
| 401 |
It is possible to specify the required argument types of functions exported from |
| 402 |
DLLs by setting the :attr:`argtypes` attribute. |
| 403 |
|
| 404 |
:attr:`argtypes` must be a sequence of C data types (the ``printf`` function is |
| 405 |
probably not a good example here, because it takes a variable number and |
| 406 |
different types of parameters depending on the format string, on the other hand |
| 407 |
this is quite handy to experiment with this feature):: |
| 408 |
|
| 409 |
>>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double] |
| 410 |
>>> printf("String '%s', Int %d, Double %f\n", "Hi", 10, 2.2) |
| 411 |
String 'Hi', Int 10, Double 2.200000 |
| 412 |
37 |
| 413 |
>>> |
| 414 |
|
| 415 |
Specifying a format protects against incompatible argument types (just as a |
| 416 |
prototype for a C function), and tries to convert the arguments to valid types:: |
| 417 |
|
| 418 |
>>> printf("%d %d %d", 1, 2, 3) |
| 419 |
Traceback (most recent call last): |
| 420 |
File "<stdin>", line 1, in <module> |
| 421 |
ArgumentError: argument 2: exceptions.TypeError: wrong type |
| 422 |
>>> printf("%s %d %f\n", "X", 2, 3) |
| 423 |
X 2 3.000000 |
| 424 |
13 |
| 425 |
>>> |
| 426 |
|
| 427 |
If you have defined your own classes which you pass to function calls, you have |
| 428 |
to implement a :meth:`from_param` class method for them to be able to use them |
| 429 |
in the :attr:`argtypes` sequence. The :meth:`from_param` class method receives |
| 430 |
the Python object passed to the function call, it should do a typecheck or |
| 431 |
whatever is needed to make sure this object is acceptable, and then return the |
| 432 |
object itself, its :attr:`_as_parameter_` attribute, or whatever you want to |
| 433 |
pass as the C function argument in this case. Again, the result should be an |
| 434 |
integer, string, unicode, a :mod:`ctypes` instance, or an object with an |
| 435 |
:attr:`_as_parameter_` attribute. |
| 436 |
|
| 437 |
|
| 438 |
.. _ctypes-return-types: |
| 439 |
|
| 440 |
Return types |
| 441 |
^^^^^^^^^^^^ |
| 442 |
|
| 443 |
By default functions are assumed to return the C :c:type:`int` type. Other |
| 444 |
return types can be specified by setting the :attr:`restype` attribute of the |
| 445 |
function object. |
| 446 |
|
| 447 |
Here is a more advanced example, it uses the ``strchr`` function, which expects |
| 448 |
a string pointer and a char, and returns a pointer to a string:: |
| 449 |
|
| 450 |
>>> strchr = libc.strchr |
| 451 |
>>> strchr("abcdef", ord("d")) # doctest: +SKIP |
| 452 |
8059983 |
| 453 |
>>> strchr.restype = c_char_p # c_char_p is a pointer to a string |
| 454 |
>>> strchr("abcdef", ord("d")) |
| 455 |
'def' |
| 456 |
>>> print strchr("abcdef", ord("x")) |
| 457 |
None |
| 458 |
>>> |
| 459 |
|
| 460 |
If you want to avoid the ``ord("x")`` calls above, you can set the |
| 461 |
:attr:`argtypes` attribute, and the second argument will be converted from a |
| 462 |
single character Python string into a C char:: |
| 463 |
|
| 464 |
>>> strchr.restype = c_char_p |
| 465 |
>>> strchr.argtypes = [c_char_p, c_char] |
| 466 |
>>> strchr("abcdef", "d") |
| 467 |
'def' |
| 468 |
>>> strchr("abcdef", "def") |
| 469 |
Traceback (most recent call last): |
| 470 |
File "<stdin>", line 1, in <module> |
| 471 |
ArgumentError: argument 2: exceptions.TypeError: one character string expected |
| 472 |
>>> print strchr("abcdef", "x") |
| 473 |
None |
| 474 |
>>> strchr("abcdef", "d") |
| 475 |
'def' |
| 476 |
>>> |
| 477 |
|
| 478 |
You can also use a callable Python object (a function or a class for example) as |
| 479 |
the :attr:`restype` attribute, if the foreign function returns an integer. The |
| 480 |
callable will be called with the *integer* the C function returns, and the |
| 481 |
result of this call will be used as the result of your function call. This is |
| 482 |
useful to check for error return values and automatically raise an exception:: |
| 483 |
|
| 484 |
>>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS |
| 485 |
>>> def ValidHandle(value): |
| 486 |
... if value == 0: |
| 487 |
... raise WinError() |
| 488 |
... return value |
| 489 |
... |
| 490 |
>>> |
| 491 |
>>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS |
| 492 |
>>> GetModuleHandle(None) # doctest: +WINDOWS |
| 493 |
486539264 |
| 494 |
>>> GetModuleHandle("something silly") # doctest: +WINDOWS |
| 495 |
Traceback (most recent call last): |
| 496 |
File "<stdin>", line 1, in <module> |
| 497 |
File "<stdin>", line 3, in ValidHandle |
| 498 |
WindowsError: [Errno 126] The specified module could not be found. |
| 499 |
>>> |
| 500 |
|
| 501 |
``WinError`` is a function which will call Windows ``FormatMessage()`` api to |
| 502 |
get the string representation of an error code, and *returns* an exception. |
| 503 |
``WinError`` takes an optional error code parameter, if no one is used, it calls |
| 504 |
:func:`GetLastError` to retrieve it. |
| 505 |
|
| 506 |
Please note that a much more powerful error checking mechanism is available |
| 507 |
through the :attr:`errcheck` attribute; see the reference manual for details. |
| 508 |
|
| 509 |
|
| 510 |
.. _ctypes-passing-pointers: |
| 511 |
|
| 512 |
Passing pointers (or: passing parameters by reference) |
| 513 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 514 |
|
| 515 |
Sometimes a C api function expects a *pointer* to a data type as parameter, |
| 516 |
probably to write into the corresponding location, or if the data is too large |
| 517 |
to be passed by value. This is also known as *passing parameters by reference*. |
| 518 |
|
| 519 |
:mod:`ctypes` exports the :func:`byref` function which is used to pass |
| 520 |
parameters by reference. The same effect can be achieved with the |
| 521 |
:func:`pointer` function, although :func:`pointer` does a lot more work since it |
| 522 |
constructs a real pointer object, so it is faster to use :func:`byref` if you |
| 523 |
don't need the pointer object in Python itself:: |
| 524 |
|
| 525 |
>>> i = c_int() |
| 526 |
>>> f = c_float() |
| 527 |
>>> s = create_string_buffer('\000' * 32) |
| 528 |
>>> print i.value, f.value, repr(s.value) |
| 529 |
0 0.0 '' |
| 530 |
>>> libc.sscanf("1 3.14 Hello", "%d %f %s", |
| 531 |
... byref(i), byref(f), s) |
| 532 |
3 |
| 533 |
>>> print i.value, f.value, repr(s.value) |
| 534 |
1 3.1400001049 'Hello' |
| 535 |
>>> |
| 536 |
|
| 537 |
|
| 538 |
.. _ctypes-structures-unions: |
| 539 |
|
| 540 |
Structures and unions |
| 541 |
^^^^^^^^^^^^^^^^^^^^^ |
| 542 |
|
| 543 |
Structures and unions must derive from the :class:`Structure` and :class:`Union` |
| 544 |
base classes which are defined in the :mod:`ctypes` module. Each subclass must |
| 545 |
define a :attr:`_fields_` attribute. :attr:`_fields_` must be a list of |
| 546 |
*2-tuples*, containing a *field name* and a *field type*. |
| 547 |
|
| 548 |
The field type must be a :mod:`ctypes` type like :class:`c_int`, or any other |
| 549 |
derived :mod:`ctypes` type: structure, union, array, pointer. |
| 550 |
|
| 551 |
Here is a simple example of a POINT structure, which contains two integers named |
| 552 |
*x* and *y*, and also shows how to initialize a structure in the constructor:: |
| 553 |
|
| 554 |
>>> from ctypes import * |
| 555 |
>>> class POINT(Structure): |
| 556 |
... _fields_ = [("x", c_int), |
| 557 |
... ("y", c_int)] |
| 558 |
... |
| 559 |
>>> point = POINT(10, 20) |
| 560 |
>>> print point.x, point.y |
| 561 |
10 20 |
| 562 |
>>> point = POINT(y=5) |
| 563 |
>>> print point.x, point.y |
| 564 |
0 5 |
| 565 |
>>> POINT(1, 2, 3) |
| 566 |
Traceback (most recent call last): |
| 567 |
File "<stdin>", line 1, in <module> |
| 568 |
TypeError: too many initializers |
| 569 |
>>> |
| 570 |
|
| 571 |
You can, however, build much more complicated structures. A structure can |
| 572 |
itself contain other structures by using a structure as a field type. |
| 573 |
|
| 574 |
Here is a RECT structure which contains two POINTs named *upperleft* and |
| 575 |
*lowerright*:: |
| 576 |
|
| 577 |
>>> class RECT(Structure): |
| 578 |
... _fields_ = [("upperleft", POINT), |
| 579 |
... ("lowerright", POINT)] |
| 580 |
... |
| 581 |
>>> rc = RECT(point) |
| 582 |
>>> print rc.upperleft.x, rc.upperleft.y |
| 583 |
0 5 |
| 584 |
>>> print rc.lowerright.x, rc.lowerright.y |
| 585 |
0 0 |
| 586 |
>>> |
| 587 |
|
| 588 |
Nested structures can also be initialized in the constructor in several ways:: |
| 589 |
|
| 590 |
>>> r = RECT(POINT(1, 2), POINT(3, 4)) |
| 591 |
>>> r = RECT((1, 2), (3, 4)) |
| 592 |
|
| 593 |
Field :term:`descriptor`\s can be retrieved from the *class*, they are useful |
| 594 |
for debugging because they can provide useful information:: |
| 595 |
|
| 596 |
>>> print POINT.x |
| 597 |
<Field type=c_long, ofs=0, size=4> |
| 598 |
>>> print POINT.y |
| 599 |
<Field type=c_long, ofs=4, size=4> |
| 600 |
>>> |
| 601 |
|
| 602 |
|
| 603 |
.. _ctypes-structureunion-alignment-byte-order: |
| 604 |
|
| 605 |
.. warning:: |
| 606 |
|
| 607 |
:mod:`ctypes` does not support passing unions or structures with bit-fields |
| 608 |
to functions by value. While this may work on 32-bit x86, it's not |
| 609 |
guaranteed by the library to work in the general case. Unions and |
| 610 |
structures with bit-fields should always be passed to functions by pointer. |
| 611 |
|
| 612 |
Structure/union alignment and byte order |
| 613 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 614 |
|
| 615 |
By default, Structure and Union fields are aligned in the same way the C |
| 616 |
compiler does it. It is possible to override this behavior be specifying a |
| 617 |
:attr:`_pack_` class attribute in the subclass definition. This must be set to a |
| 618 |
positive integer and specifies the maximum alignment for the fields. This is |
| 619 |
what ``#pragma pack(n)`` also does in MSVC. |
| 620 |
|
| 621 |
:mod:`ctypes` uses the native byte order for Structures and Unions. To build |
| 622 |
structures with non-native byte order, you can use one of the |
| 623 |
:class:`BigEndianStructure`, :class:`LittleEndianStructure`, |
| 624 |
:class:`BigEndianUnion`, and :class:`LittleEndianUnion` base classes. These |
| 625 |
classes cannot contain pointer fields. |
| 626 |
|
| 627 |
|
| 628 |
.. _ctypes-bit-fields-in-structures-unions: |
| 629 |
|
| 630 |
Bit fields in structures and unions |
| 631 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 632 |
|
| 633 |
It is possible to create structures and unions containing bit fields. Bit fields |
| 634 |
are only possible for integer fields, the bit width is specified as the third |
| 635 |
item in the :attr:`_fields_` tuples:: |
| 636 |
|
| 637 |
>>> class Int(Structure): |
| 638 |
... _fields_ = [("first_16", c_int, 16), |
| 639 |
... ("second_16", c_int, 16)] |
| 640 |
... |
| 641 |
>>> print Int.first_16 |
| 642 |
<Field type=c_long, ofs=0:0, bits=16> |
| 643 |
>>> print Int.second_16 |
| 644 |
<Field type=c_long, ofs=0:16, bits=16> |
| 645 |
>>> |
| 646 |
|
| 647 |
|
| 648 |
.. _ctypes-arrays: |
| 649 |
|
| 650 |
Arrays |
| 651 |
^^^^^^ |
| 652 |
|
| 653 |
Arrays are sequences, containing a fixed number of instances of the same type. |
| 654 |
|
| 655 |
The recommended way to create array types is by multiplying a data type with a |
| 656 |
positive integer:: |
| 657 |
|
| 658 |
TenPointsArrayType = POINT * 10 |
| 659 |
|
| 660 |
Here is an example of a somewhat artificial data type, a structure containing 4 |
| 661 |
POINTs among other stuff:: |
| 662 |
|
| 663 |
>>> from ctypes import * |
| 664 |
>>> class POINT(Structure): |
| 665 |
... _fields_ = ("x", c_int), ("y", c_int) |
| 666 |
... |
| 667 |
>>> class MyStruct(Structure): |
| 668 |
... _fields_ = [("a", c_int), |
| 669 |
... ("b", c_float), |
| 670 |
... ("point_array", POINT * 4)] |
| 671 |
>>> |
| 672 |
>>> print len(MyStruct().point_array) |
| 673 |
4 |
| 674 |
>>> |
| 675 |
|
| 676 |
Instances are created in the usual way, by calling the class:: |
| 677 |
|
| 678 |
arr = TenPointsArrayType() |
| 679 |
for pt in arr: |
| 680 |
print pt.x, pt.y |
| 681 |
|
| 682 |
The above code print a series of ``0 0`` lines, because the array contents is |
| 683 |
initialized to zeros. |
| 684 |
|
| 685 |
Initializers of the correct type can also be specified:: |
| 686 |
|
| 687 |
>>> from ctypes import * |
| 688 |
>>> TenIntegers = c_int * 10 |
| 689 |
>>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) |
| 690 |
>>> print ii |
| 691 |
<c_long_Array_10 object at 0x...> |
| 692 |
>>> for i in ii: print i, |
| 693 |
... |
| 694 |
1 2 3 4 5 6 7 8 9 10 |
| 695 |
>>> |
| 696 |
|
| 697 |
|
| 698 |
.. _ctypes-pointers: |
| 699 |
|
| 700 |
Pointers |
| 701 |
^^^^^^^^ |
| 702 |
|
| 703 |
Pointer instances are created by calling the :func:`pointer` function on a |
| 704 |
:mod:`ctypes` type:: |
| 705 |
|
| 706 |
>>> from ctypes import * |
| 707 |
>>> i = c_int(42) |
| 708 |
>>> pi = pointer(i) |
| 709 |
>>> |
| 710 |
|
| 711 |
Pointer instances have a :attr:`~_Pointer.contents` attribute which |
| 712 |
returns the object to which the pointer points, the ``i`` object above:: |
| 713 |
|
| 714 |
>>> pi.contents |
| 715 |
c_long(42) |
| 716 |
>>> |
| 717 |
|
| 718 |
Note that :mod:`ctypes` does not have OOR (original object return), it constructs a |
| 719 |
new, equivalent object each time you retrieve an attribute:: |
| 720 |
|
| 721 |
>>> pi.contents is i |
| 722 |
False |
| 723 |
>>> pi.contents is pi.contents |
| 724 |
False |
| 725 |
>>> |
| 726 |
|
| 727 |
Assigning another :class:`c_int` instance to the pointer's contents attribute |
| 728 |
would cause the pointer to point to the memory location where this is stored:: |
| 729 |
|
| 730 |
>>> i = c_int(99) |
| 731 |
>>> pi.contents = i |
| 732 |
>>> pi.contents |
| 733 |
c_long(99) |
| 734 |
>>> |
| 735 |
|
| 736 |
.. XXX Document dereferencing pointers, and that it is preferred over the |
| 737 |
.contents attribute. |
| 738 |
|
| 739 |
Pointer instances can also be indexed with integers:: |
| 740 |
|
| 741 |
>>> pi[0] |
| 742 |
99 |
| 743 |
>>> |
| 744 |
|
| 745 |
Assigning to an integer index changes the pointed to value:: |
| 746 |
|
| 747 |
>>> print i |
| 748 |
c_long(99) |
| 749 |
>>> pi[0] = 22 |
| 750 |
>>> print i |
| 751 |
c_long(22) |
| 752 |
>>> |
| 753 |
|
| 754 |
It is also possible to use indexes different from 0, but you must know what |
| 755 |
you're doing, just as in C: You can access or change arbitrary memory locations. |
| 756 |
Generally you only use this feature if you receive a pointer from a C function, |
| 757 |
and you *know* that the pointer actually points to an array instead of a single |
| 758 |
item. |
| 759 |
|
| 760 |
Behind the scenes, the :func:`pointer` function does more than simply create |
| 761 |
pointer instances, it has to create pointer *types* first. This is done with |
| 762 |
the :func:`POINTER` function, which accepts any :mod:`ctypes` type, and returns |
| 763 |
a new type:: |
| 764 |
|
| 765 |
>>> PI = POINTER(c_int) |
| 766 |
>>> PI |
| 767 |
<class 'ctypes.LP_c_long'> |
| 768 |
>>> PI(42) |
| 769 |
Traceback (most recent call last): |
| 770 |
File "<stdin>", line 1, in <module> |
| 771 |
TypeError: expected c_long instead of int |
| 772 |
>>> PI(c_int(42)) |
| 773 |
<ctypes.LP_c_long object at 0x...> |
| 774 |
>>> |
| 775 |
|
| 776 |
Calling the pointer type without an argument creates a ``NULL`` pointer. |
| 777 |
``NULL`` pointers have a ``False`` boolean value:: |
| 778 |
|
| 779 |
>>> null_ptr = POINTER(c_int)() |
| 780 |
>>> print bool(null_ptr) |
| 781 |
False |
| 782 |
>>> |
| 783 |
|
| 784 |
:mod:`ctypes` checks for ``NULL`` when dereferencing pointers (but dereferencing |
| 785 |
invalid non-\ ``NULL`` pointers would crash Python):: |
| 786 |
|
| 787 |
>>> null_ptr[0] |
| 788 |
Traceback (most recent call last): |
| 789 |
.... |
| 790 |
ValueError: NULL pointer access |
| 791 |
>>> |
| 792 |
|
| 793 |
>>> null_ptr[0] = 1234 |
| 794 |
Traceback (most recent call last): |
| 795 |
.... |
| 796 |
ValueError: NULL pointer access |
| 797 |
>>> |
| 798 |
|
| 799 |
|
| 800 |
.. _ctypes-type-conversions: |
| 801 |
|
| 802 |
Type conversions |
| 803 |
^^^^^^^^^^^^^^^^ |
| 804 |
|
| 805 |
Usually, ctypes does strict type checking. This means, if you have |
| 806 |
``POINTER(c_int)`` in the :attr:`argtypes` list of a function or as the type of |
| 807 |
a member field in a structure definition, only instances of exactly the same |
| 808 |
type are accepted. There are some exceptions to this rule, where ctypes accepts |
| 809 |
other objects. For example, you can pass compatible array instances instead of |
| 810 |
pointer types. So, for ``POINTER(c_int)``, ctypes accepts an array of c_int:: |
| 811 |
|
| 812 |
>>> class Bar(Structure): |
| 813 |
... _fields_ = [("count", c_int), ("values", POINTER(c_int))] |
| 814 |
... |
| 815 |
>>> bar = Bar() |
| 816 |
>>> bar.values = (c_int * 3)(1, 2, 3) |
| 817 |
>>> bar.count = 3 |
| 818 |
>>> for i in range(bar.count): |
| 819 |
... print bar.values[i] |
| 820 |
... |
| 821 |
1 |
| 822 |
2 |
| 823 |
3 |
| 824 |
>>> |
| 825 |
|
| 826 |
In addition, if a function argument is explicitly declared to be a pointer type |
| 827 |
(such as ``POINTER(c_int)``) in :attr:`argtypes`, an object of the pointed |
| 828 |
type (``c_int`` in this case) can be passed to the function. ctypes will apply |
| 829 |
the required :func:`byref` conversion in this case automatically. |
| 830 |
|
| 831 |
To set a POINTER type field to ``NULL``, you can assign ``None``:: |
| 832 |
|
| 833 |
>>> bar.values = None |
| 834 |
>>> |
| 835 |
|
| 836 |
.. XXX list other conversions... |
| 837 |
|
| 838 |
Sometimes you have instances of incompatible types. In C, you can cast one type |
| 839 |
into another type. :mod:`ctypes` provides a :func:`cast` function which can be |
| 840 |
used in the same way. The ``Bar`` structure defined above accepts |
| 841 |
``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field, |
| 842 |
but not instances of other types:: |
| 843 |
|
| 844 |
>>> bar.values = (c_byte * 4)() |
| 845 |
Traceback (most recent call last): |
| 846 |
File "<stdin>", line 1, in <module> |
| 847 |
TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance |
| 848 |
>>> |
| 849 |
|
| 850 |
For these cases, the :func:`cast` function is handy. |
| 851 |
|
| 852 |
The :func:`cast` function can be used to cast a ctypes instance into a pointer |
| 853 |
to a different ctypes data type. :func:`cast` takes two parameters, a ctypes |
| 854 |
object that is or can be converted to a pointer of some kind, and a ctypes |
| 855 |
pointer type. It returns an instance of the second argument, which references |
| 856 |
the same memory block as the first argument:: |
| 857 |
|
| 858 |
>>> a = (c_byte * 4)() |
| 859 |
>>> cast(a, POINTER(c_int)) |
| 860 |
<ctypes.LP_c_long object at ...> |
| 861 |
>>> |
| 862 |
|
| 863 |
So, :func:`cast` can be used to assign to the ``values`` field of ``Bar`` the |
| 864 |
structure:: |
| 865 |
|
| 866 |
>>> bar = Bar() |
| 867 |
>>> bar.values = cast((c_byte * 4)(), POINTER(c_int)) |
| 868 |
>>> print bar.values[0] |
| 869 |
0 |
| 870 |
>>> |
| 871 |
|
| 872 |
|
| 873 |
.. _ctypes-incomplete-types: |
| 874 |
|
| 875 |
Incomplete Types |
| 876 |
^^^^^^^^^^^^^^^^ |
| 877 |
|
| 878 |
*Incomplete Types* are structures, unions or arrays whose members are not yet |
| 879 |
specified. In C, they are specified by forward declarations, which are defined |
| 880 |
later:: |
| 881 |
|
| 882 |
struct cell; /* forward declaration */ |
| 883 |
|
| 884 |
struct cell { |
| 885 |
char *name; |
| 886 |
struct cell *next; |
| 887 |
}; |
| 888 |
|
| 889 |
The straightforward translation into ctypes code would be this, but it does not |
| 890 |
work:: |
| 891 |
|
| 892 |
>>> class cell(Structure): |
| 893 |
... _fields_ = [("name", c_char_p), |
| 894 |
... ("next", POINTER(cell))] |
| 895 |
... |
| 896 |
Traceback (most recent call last): |
| 897 |
File "<stdin>", line 1, in <module> |
| 898 |
File "<stdin>", line 2, in cell |
| 899 |
NameError: name 'cell' is not defined |
| 900 |
>>> |
| 901 |
|
| 902 |
because the new ``class cell`` is not available in the class statement itself. |
| 903 |
In :mod:`ctypes`, we can define the ``cell`` class and set the :attr:`_fields_` |
| 904 |
attribute later, after the class statement:: |
| 905 |
|
| 906 |
>>> from ctypes import * |
| 907 |
>>> class cell(Structure): |
| 908 |
... pass |
| 909 |
... |
| 910 |
>>> cell._fields_ = [("name", c_char_p), |
| 911 |
... ("next", POINTER(cell))] |
| 912 |
>>> |
| 913 |
|
| 914 |
Lets try it. We create two instances of ``cell``, and let them point to each |
| 915 |
other, and finally follow the pointer chain a few times:: |
| 916 |
|
| 917 |
>>> c1 = cell() |
| 918 |
>>> c1.name = "foo" |
| 919 |
>>> c2 = cell() |
| 920 |
>>> c2.name = "bar" |
| 921 |
>>> c1.next = pointer(c2) |
| 922 |
>>> c2.next = pointer(c1) |
| 923 |
>>> p = c1 |
| 924 |
>>> for i in range(8): |
| 925 |
... print p.name, |
| 926 |
... p = p.next[0] |
| 927 |
... |
| 928 |
foo bar foo bar foo bar foo bar |
| 929 |
>>> |
| 930 |
|
| 931 |
|
| 932 |
.. _ctypes-callback-functions: |
| 933 |
|
| 934 |
Callback functions |
| 935 |
^^^^^^^^^^^^^^^^^^ |
| 936 |
|
| 937 |
:mod:`ctypes` allows creating C callable function pointers from Python callables. |
| 938 |
These are sometimes called *callback functions*. |
| 939 |
|
| 940 |
First, you must create a class for the callback function, the class knows the |
| 941 |
calling convention, the return type, and the number and types of arguments this |
| 942 |
function will receive. |
| 943 |
|
| 944 |
The CFUNCTYPE factory function creates types for callback functions using the |
| 945 |
normal cdecl calling convention, and, on Windows, the WINFUNCTYPE factory |
| 946 |
function creates types for callback functions using the stdcall calling |
| 947 |
convention. |
| 948 |
|
| 949 |
Both of these factory functions are called with the result type as first |
| 950 |
argument, and the callback functions expected argument types as the remaining |
| 951 |
arguments. |
| 952 |
|
| 953 |
I will present an example here which uses the standard C library's :func:`qsort` |
| 954 |
function, this is used to sort items with the help of a callback function. |
| 955 |
:func:`qsort` will be used to sort an array of integers:: |
| 956 |
|
| 957 |
>>> IntArray5 = c_int * 5 |
| 958 |
>>> ia = IntArray5(5, 1, 7, 33, 99) |
| 959 |
>>> qsort = libc.qsort |
| 960 |
>>> qsort.restype = None |
| 961 |
>>> |
| 962 |
|
| 963 |
:func:`qsort` must be called with a pointer to the data to sort, the number of |
| 964 |
items in the data array, the size of one item, and a pointer to the comparison |
| 965 |
function, the callback. The callback will then be called with two pointers to |
| 966 |
items, and it must return a negative integer if the first item is smaller than |
| 967 |
the second, a zero if they are equal, and a positive integer else. |
| 968 |
|
| 969 |
So our callback function receives pointers to integers, and must return an |
| 970 |
integer. First we create the ``type`` for the callback function:: |
| 971 |
|
| 972 |
>>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int)) |
| 973 |
>>> |
| 974 |
|
| 975 |
For the first implementation of the callback function, we simply print the |
| 976 |
arguments we get, and return 0 (incremental development ;-):: |
| 977 |
|
| 978 |
>>> def py_cmp_func(a, b): |
| 979 |
... print "py_cmp_func", a, b |
| 980 |
... return 0 |
| 981 |
... |
| 982 |
>>> |
| 983 |
|
| 984 |
Create the C callable callback:: |
| 985 |
|
| 986 |
>>> cmp_func = CMPFUNC(py_cmp_func) |
| 987 |
>>> |
| 988 |
|
| 989 |
And we're ready to go:: |
| 990 |
|
| 991 |
>>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS |
| 992 |
py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...> |
| 993 |
py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...> |
| 994 |
py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...> |
| 995 |
py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...> |
| 996 |
py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...> |
| 997 |
py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...> |
| 998 |
py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...> |
| 999 |
py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...> |
| 1000 |
py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...> |
| 1001 |
py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...> |
| 1002 |
>>> |
| 1003 |
|
| 1004 |
We know how to access the contents of a pointer, so lets redefine our callback:: |
| 1005 |
|
| 1006 |
>>> def py_cmp_func(a, b): |
| 1007 |
... print "py_cmp_func", a[0], b[0] |
| 1008 |
... return 0 |
| 1009 |
... |
| 1010 |
>>> cmp_func = CMPFUNC(py_cmp_func) |
| 1011 |
>>> |
| 1012 |
|
| 1013 |
Here is what we get on Windows:: |
| 1014 |
|
| 1015 |
>>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS |
| 1016 |
py_cmp_func 7 1 |
| 1017 |
py_cmp_func 33 1 |
| 1018 |
py_cmp_func 99 1 |
| 1019 |
py_cmp_func 5 1 |
| 1020 |
py_cmp_func 7 5 |
| 1021 |
py_cmp_func 33 5 |
| 1022 |
py_cmp_func 99 5 |
| 1023 |
py_cmp_func 7 99 |
| 1024 |
py_cmp_func 33 99 |
| 1025 |
py_cmp_func 7 33 |
| 1026 |
>>> |
| 1027 |
|
| 1028 |
It is funny to see that on linux the sort function seems to work much more |
| 1029 |
efficiently, it is doing less comparisons:: |
| 1030 |
|
| 1031 |
>>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX |
| 1032 |
py_cmp_func 5 1 |
| 1033 |
py_cmp_func 33 99 |
| 1034 |
py_cmp_func 7 33 |
| 1035 |
py_cmp_func 5 7 |
| 1036 |
py_cmp_func 1 7 |
| 1037 |
>>> |
| 1038 |
|
| 1039 |
Ah, we're nearly done! The last step is to actually compare the two items and |
| 1040 |
return a useful result:: |
| 1041 |
|
| 1042 |
>>> def py_cmp_func(a, b): |
| 1043 |
... print "py_cmp_func", a[0], b[0] |
| 1044 |
... return a[0] - b[0] |
| 1045 |
... |
| 1046 |
>>> |
| 1047 |
|
| 1048 |
Final run on Windows:: |
| 1049 |
|
| 1050 |
>>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +WINDOWS |
| 1051 |
py_cmp_func 33 7 |
| 1052 |
py_cmp_func 99 33 |
| 1053 |
py_cmp_func 5 99 |
| 1054 |
py_cmp_func 1 99 |
| 1055 |
py_cmp_func 33 7 |
| 1056 |
py_cmp_func 1 33 |
| 1057 |
py_cmp_func 5 33 |
| 1058 |
py_cmp_func 5 7 |
| 1059 |
py_cmp_func 1 7 |
| 1060 |
py_cmp_func 5 1 |
| 1061 |
>>> |
| 1062 |
|
| 1063 |
and on Linux:: |
| 1064 |
|
| 1065 |
>>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX |
| 1066 |
py_cmp_func 5 1 |
| 1067 |
py_cmp_func 33 99 |
| 1068 |
py_cmp_func 7 33 |
| 1069 |
py_cmp_func 1 7 |
| 1070 |
py_cmp_func 5 7 |
| 1071 |
>>> |
| 1072 |
|
| 1073 |
It is quite interesting to see that the Windows :func:`qsort` function needs |
| 1074 |
more comparisons than the linux version! |
| 1075 |
|
| 1076 |
As we can easily check, our array is sorted now:: |
| 1077 |
|
| 1078 |
>>> for i in ia: print i, |
| 1079 |
... |
| 1080 |
1 5 7 33 99 |
| 1081 |
>>> |
| 1082 |
|
| 1083 |
.. note:: |
| 1084 |
|
| 1085 |
Make sure you keep references to :func:`CFUNCTYPE` objects as long as they |
| 1086 |
are used from C code. :mod:`ctypes` doesn't, and if you don't, they may be |
| 1087 |
garbage collected, crashing your program when a callback is made. |
| 1088 |
|
| 1089 |
Also, note that if the callback function is called in a thread created |
| 1090 |
outside of Python's control (e.g. by the foreign code that calls the |
| 1091 |
callback), ctypes creates a new dummy Python thread on every invocation. This |
| 1092 |
behavior is correct for most purposes, but it means that values stored with |
| 1093 |
:class:`threading.local` will *not* survive across different callbacks, even when |
| 1094 |
those calls are made from the same C thread. |
| 1095 |
|
| 1096 |
.. _ctypes-accessing-values-exported-from-dlls: |
| 1097 |
|
| 1098 |
Accessing values exported from dlls |
| 1099 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1100 |
|
| 1101 |
Some shared libraries not only export functions, they also export variables. An |
| 1102 |
example in the Python library itself is the ``Py_OptimizeFlag``, an integer set |
| 1103 |
to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on |
| 1104 |
startup. |
| 1105 |
|
| 1106 |
:mod:`ctypes` can access values like this with the :meth:`in_dll` class methods of |
| 1107 |
the type. *pythonapi* is a predefined symbol giving access to the Python C |
| 1108 |
api:: |
| 1109 |
|
| 1110 |
>>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag") |
| 1111 |
>>> print opt_flag |
| 1112 |
c_long(0) |
| 1113 |
>>> |
| 1114 |
|
| 1115 |
If the interpreter would have been started with :option:`-O`, the sample would |
| 1116 |
have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been |
| 1117 |
specified. |
| 1118 |
|
| 1119 |
An extended example which also demonstrates the use of pointers accesses the |
| 1120 |
``PyImport_FrozenModules`` pointer exported by Python. |
| 1121 |
|
| 1122 |
Quoting the Python docs: *This pointer is initialized to point to an array of |
| 1123 |
"struct _frozen" records, terminated by one whose members are all NULL or zero. |
| 1124 |
When a frozen module is imported, it is searched in this table. Third-party code |
| 1125 |
could play tricks with this to provide a dynamically created collection of |
| 1126 |
frozen modules.* |
| 1127 |
|
| 1128 |
So manipulating this pointer could even prove useful. To restrict the example |
| 1129 |
size, we show only how this table can be read with :mod:`ctypes`:: |
| 1130 |
|
| 1131 |
>>> from ctypes import * |
| 1132 |
>>> |
| 1133 |
>>> class struct_frozen(Structure): |
| 1134 |
... _fields_ = [("name", c_char_p), |
| 1135 |
... ("code", POINTER(c_ubyte)), |
| 1136 |
... ("size", c_int)] |
| 1137 |
... |
| 1138 |
>>> |
| 1139 |
|
| 1140 |
We have defined the ``struct _frozen`` data type, so we can get the pointer to |
| 1141 |
the table:: |
| 1142 |
|
| 1143 |
>>> FrozenTable = POINTER(struct_frozen) |
| 1144 |
>>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules") |
| 1145 |
>>> |
| 1146 |
|
| 1147 |
Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we |
| 1148 |
can iterate over it, but we just have to make sure that our loop terminates, |
| 1149 |
because pointers have no size. Sooner or later it would probably crash with an |
| 1150 |
access violation or whatever, so it's better to break out of the loop when we |
| 1151 |
hit the NULL entry:: |
| 1152 |
|
| 1153 |
>>> for item in table: |
| 1154 |
... print item.name, item.size |
| 1155 |
... if item.name is None: |
| 1156 |
... break |
| 1157 |
... |
| 1158 |
__hello__ 104 |
| 1159 |
__phello__ -104 |
| 1160 |
__phello__.spam 104 |
| 1161 |
None 0 |
| 1162 |
>>> |
| 1163 |
|
| 1164 |
The fact that standard Python has a frozen module and a frozen package |
| 1165 |
(indicated by the negative size member) is not well known, it is only used for |
| 1166 |
testing. Try it out with ``import __hello__`` for example. |
| 1167 |
|
| 1168 |
|
| 1169 |
.. _ctypes-surprises: |
| 1170 |
|
| 1171 |
Surprises |
| 1172 |
^^^^^^^^^ |
| 1173 |
|
| 1174 |
There are some edge cases in :mod:`ctypes` where you might expect something |
| 1175 |
other than what actually happens. |
| 1176 |
|
| 1177 |
Consider the following example:: |
| 1178 |
|
| 1179 |
>>> from ctypes import * |
| 1180 |
>>> class POINT(Structure): |
| 1181 |
... _fields_ = ("x", c_int), ("y", c_int) |
| 1182 |
... |
| 1183 |
>>> class RECT(Structure): |
| 1184 |
... _fields_ = ("a", POINT), ("b", POINT) |
| 1185 |
... |
| 1186 |
>>> p1 = POINT(1, 2) |
| 1187 |
>>> p2 = POINT(3, 4) |
| 1188 |
>>> rc = RECT(p1, p2) |
| 1189 |
>>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y |
| 1190 |
1 2 3 4 |
| 1191 |
>>> # now swap the two points |
| 1192 |
>>> rc.a, rc.b = rc.b, rc.a |
| 1193 |
>>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y |
| 1194 |
3 4 3 4 |
| 1195 |
>>> |
| 1196 |
|
| 1197 |
Hm. We certainly expected the last statement to print ``3 4 1 2``. What |
| 1198 |
happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above:: |
| 1199 |
|
| 1200 |
>>> temp0, temp1 = rc.b, rc.a |
| 1201 |
>>> rc.a = temp0 |
| 1202 |
>>> rc.b = temp1 |
| 1203 |
>>> |
| 1204 |
|
| 1205 |
Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of |
| 1206 |
the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer |
| 1207 |
contents of ``temp0`` into ``rc`` 's buffer. This, in turn, changes the |
| 1208 |
contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have |
| 1209 |
the expected effect. |
| 1210 |
|
| 1211 |
Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays |
| 1212 |
doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing |
| 1213 |
the root-object's underlying buffer. |
| 1214 |
|
| 1215 |
Another example that may behave different from what one would expect is this:: |
| 1216 |
|
| 1217 |
>>> s = c_char_p() |
| 1218 |
>>> s.value = "abc def ghi" |
| 1219 |
>>> s.value |
| 1220 |
'abc def ghi' |
| 1221 |
>>> s.value is s.value |
| 1222 |
False |
| 1223 |
>>> |
| 1224 |
|
| 1225 |
Why is it printing ``False``? ctypes instances are objects containing a memory |
| 1226 |
block plus some :term:`descriptor`\s accessing the contents of the memory. |
| 1227 |
Storing a Python object in the memory block does not store the object itself, |
| 1228 |
instead the ``contents`` of the object is stored. Accessing the contents again |
| 1229 |
constructs a new Python object each time! |
| 1230 |
|
| 1231 |
|
| 1232 |
.. _ctypes-variable-sized-data-types: |
| 1233 |
|
| 1234 |
Variable-sized data types |
| 1235 |
^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1236 |
|
| 1237 |
:mod:`ctypes` provides some support for variable-sized arrays and structures. |
| 1238 |
|
| 1239 |
The :func:`resize` function can be used to resize the memory buffer of an |
| 1240 |
existing ctypes object. The function takes the object as first argument, and |
| 1241 |
the requested size in bytes as the second argument. The memory block cannot be |
| 1242 |
made smaller than the natural memory block specified by the objects type, a |
| 1243 |
:exc:`ValueError` is raised if this is tried:: |
| 1244 |
|
| 1245 |
>>> short_array = (c_short * 4)() |
| 1246 |
>>> print sizeof(short_array) |
| 1247 |
8 |
| 1248 |
>>> resize(short_array, 4) |
| 1249 |
Traceback (most recent call last): |
| 1250 |
... |
| 1251 |
ValueError: minimum size is 8 |
| 1252 |
>>> resize(short_array, 32) |
| 1253 |
>>> sizeof(short_array) |
| 1254 |
32 |
| 1255 |
>>> sizeof(type(short_array)) |
| 1256 |
8 |
| 1257 |
>>> |
| 1258 |
|
| 1259 |
This is nice and fine, but how would one access the additional elements |
| 1260 |
contained in this array? Since the type still only knows about 4 elements, we |
| 1261 |
get errors accessing other elements:: |
| 1262 |
|
| 1263 |
>>> short_array[:] |
| 1264 |
[0, 0, 0, 0] |
| 1265 |
>>> short_array[7] |
| 1266 |
Traceback (most recent call last): |
| 1267 |
... |
| 1268 |
IndexError: invalid index |
| 1269 |
>>> |
| 1270 |
|
| 1271 |
Another way to use variable-sized data types with :mod:`ctypes` is to use the |
| 1272 |
dynamic nature of Python, and (re-)define the data type after the required size |
| 1273 |
is already known, on a case by case basis. |
| 1274 |
|
| 1275 |
|
| 1276 |
.. _ctypes-ctypes-reference: |
| 1277 |
|
| 1278 |
ctypes reference |
| 1279 |
---------------- |
| 1280 |
|
| 1281 |
|
| 1282 |
.. _ctypes-finding-shared-libraries: |
| 1283 |
|
| 1284 |
Finding shared libraries |
| 1285 |
^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1286 |
|
| 1287 |
When programming in a compiled language, shared libraries are accessed when |
| 1288 |
compiling/linking a program, and when the program is run. |
| 1289 |
|
| 1290 |
The purpose of the :func:`find_library` function is to locate a library in a way |
| 1291 |
similar to what the compiler does (on platforms with several versions of a |
| 1292 |
shared library the most recent should be loaded), while the ctypes library |
| 1293 |
loaders act like when a program is run, and call the runtime loader directly. |
| 1294 |
|
| 1295 |
The :mod:`ctypes.util` module provides a function which can help to determine the |
| 1296 |
library to load. |
| 1297 |
|
| 1298 |
|
| 1299 |
.. data:: find_library(name) |
| 1300 |
:module: ctypes.util |
| 1301 |
:noindex: |
| 1302 |
|
| 1303 |
Try to find a library and return a pathname. *name* is the library name without |
| 1304 |
any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this |
| 1305 |
is the form used for the posix linker option :option:`!-l`). If no library can |
| 1306 |
be found, returns ``None``. |
| 1307 |
|
| 1308 |
The exact functionality is system dependent. |
| 1309 |
|
| 1310 |
On Linux, :func:`find_library` tries to run external programs |
| 1311 |
(``/sbin/ldconfig``, ``gcc``, and ``objdump``) to find the library file. It |
| 1312 |
returns the filename of the library file. Here are some examples:: |
| 1313 |
|
| 1314 |
>>> from ctypes.util import find_library |
| 1315 |
>>> find_library("m") |
| 1316 |
'libm.so.6' |
| 1317 |
>>> find_library("c") |
| 1318 |
'libc.so.6' |
| 1319 |
>>> find_library("bz2") |
| 1320 |
'libbz2.so.1.0' |
| 1321 |
>>> |
| 1322 |
|
| 1323 |
On OS X, :func:`find_library` tries several predefined naming schemes and paths |
| 1324 |
to locate the library, and returns a full pathname if successful:: |
| 1325 |
|
| 1326 |
>>> from ctypes.util import find_library |
| 1327 |
>>> find_library("c") |
| 1328 |
'/usr/lib/libc.dylib' |
| 1329 |
>>> find_library("m") |
| 1330 |
'/usr/lib/libm.dylib' |
| 1331 |
>>> find_library("bz2") |
| 1332 |
'/usr/lib/libbz2.dylib' |
| 1333 |
>>> find_library("AGL") |
| 1334 |
'/System/Library/Frameworks/AGL.framework/AGL' |
| 1335 |
>>> |
| 1336 |
|
| 1337 |
On Windows, :func:`find_library` searches along the system search path, and |
| 1338 |
returns the full pathname, but since there is no predefined naming scheme a call |
| 1339 |
like ``find_library("c")`` will fail and return ``None``. |
| 1340 |
|
| 1341 |
If wrapping a shared library with :mod:`ctypes`, it *may* be better to determine |
| 1342 |
the shared library name at development time, and hardcode that into the wrapper |
| 1343 |
module instead of using :func:`find_library` to locate the library at runtime. |
| 1344 |
|
| 1345 |
|
| 1346 |
.. _ctypes-loading-shared-libraries: |
| 1347 |
|
| 1348 |
Loading shared libraries |
| 1349 |
^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1350 |
|
| 1351 |
There are several ways to load shared libraries into the Python process. One |
| 1352 |
way is to instantiate one of the following classes: |
| 1353 |
|
| 1354 |
|
| 1355 |
.. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False) |
| 1356 |
|
| 1357 |
Instances of this class represent loaded shared libraries. Functions in these |
| 1358 |
libraries use the standard C calling convention, and are assumed to return |
| 1359 |
:c:type:`int`. |
| 1360 |
|
| 1361 |
|
| 1362 |
.. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False) |
| 1363 |
|
| 1364 |
Windows only: Instances of this class represent loaded shared libraries, |
| 1365 |
functions in these libraries use the ``stdcall`` calling convention, and are |
| 1366 |
assumed to return the windows specific :class:`HRESULT` code. :class:`HRESULT` |
| 1367 |
values contain information specifying whether the function call failed or |
| 1368 |
succeeded, together with additional error code. If the return value signals a |
| 1369 |
failure, an :class:`WindowsError` is automatically raised. |
| 1370 |
|
| 1371 |
|
| 1372 |
.. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False) |
| 1373 |
|
| 1374 |
Windows only: Instances of this class represent loaded shared libraries, |
| 1375 |
functions in these libraries use the ``stdcall`` calling convention, and are |
| 1376 |
assumed to return :c:type:`int` by default. |
| 1377 |
|
| 1378 |
On Windows CE only the standard calling convention is used, for convenience the |
| 1379 |
:class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this |
| 1380 |
platform. |
| 1381 |
|
| 1382 |
The Python :term:`global interpreter lock` is released before calling any |
| 1383 |
function exported by these libraries, and reacquired afterwards. |
| 1384 |
|
| 1385 |
|
| 1386 |
.. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None) |
| 1387 |
|
| 1388 |
Instances of this class behave like :class:`CDLL` instances, except that the |
| 1389 |
Python GIL is *not* released during the function call, and after the function |
| 1390 |
execution the Python error flag is checked. If the error flag is set, a Python |
| 1391 |
exception is raised. |
| 1392 |
|
| 1393 |
Thus, this is only useful to call Python C api functions directly. |
| 1394 |
|
| 1395 |
All these classes can be instantiated by calling them with at least one |
| 1396 |
argument, the pathname of the shared library. If you have an existing handle to |
| 1397 |
an already loaded shared library, it can be passed as the ``handle`` named |
| 1398 |
parameter, otherwise the underlying platforms ``dlopen`` or ``LoadLibrary`` |
| 1399 |
function is used to load the library into the process, and to get a handle to |
| 1400 |
it. |
| 1401 |
|
| 1402 |
The *mode* parameter can be used to specify how the library is loaded. For |
| 1403 |
details, consult the :manpage:`dlopen(3)` manpage. On Windows, *mode* is |
| 1404 |
ignored. On posix systems, RTLD_NOW is always added, and is not |
| 1405 |
configurable. |
| 1406 |
|
| 1407 |
The *use_errno* parameter, when set to true, enables a ctypes mechanism that |
| 1408 |
allows accessing the system :data:`errno` error number in a safe way. |
| 1409 |
:mod:`ctypes` maintains a thread-local copy of the systems :data:`errno` |
| 1410 |
variable; if you call foreign functions created with ``use_errno=True`` then the |
| 1411 |
:data:`errno` value before the function call is swapped with the ctypes private |
| 1412 |
copy, the same happens immediately after the function call. |
| 1413 |
|
| 1414 |
The function :func:`ctypes.get_errno` returns the value of the ctypes private |
| 1415 |
copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy |
| 1416 |
to a new value and returns the former value. |
| 1417 |
|
| 1418 |
The *use_last_error* parameter, when set to true, enables the same mechanism for |
| 1419 |
the Windows error code which is managed by the :func:`GetLastError` and |
| 1420 |
:func:`SetLastError` Windows API functions; :func:`ctypes.get_last_error` and |
| 1421 |
:func:`ctypes.set_last_error` are used to request and change the ctypes private |
| 1422 |
copy of the windows error code. |
| 1423 |
|
| 1424 |
.. versionadded:: 2.6 |
| 1425 |
The *use_last_error* and *use_errno* optional parameters were added. |
| 1426 |
|
| 1427 |
.. data:: RTLD_GLOBAL |
| 1428 |
:noindex: |
| 1429 |
|
| 1430 |
Flag to use as *mode* parameter. On platforms where this flag is not available, |
| 1431 |
it is defined as the integer zero. |
| 1432 |
|
| 1433 |
|
| 1434 |
.. data:: RTLD_LOCAL |
| 1435 |
:noindex: |
| 1436 |
|
| 1437 |
Flag to use as *mode* parameter. On platforms where this is not available, it |
| 1438 |
is the same as *RTLD_GLOBAL*. |
| 1439 |
|
| 1440 |
|
| 1441 |
.. data:: DEFAULT_MODE |
| 1442 |
:noindex: |
| 1443 |
|
| 1444 |
The default mode which is used to load shared libraries. On OSX 10.3, this is |
| 1445 |
*RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*. |
| 1446 |
|
| 1447 |
Instances of these classes have no public methods. Functions exported by the |
| 1448 |
shared library can be accessed as attributes or by index. Please note that |
| 1449 |
accessing the function through an attribute caches the result and therefore |
| 1450 |
accessing it repeatedly returns the same object each time. On the other hand, |
| 1451 |
accessing it through an index returns a new object each time: |
| 1452 |
|
| 1453 |
>>> libc.time == libc.time |
| 1454 |
True |
| 1455 |
>>> libc['time'] == libc['time'] |
| 1456 |
False |
| 1457 |
|
| 1458 |
The following public attributes are available, their name starts with an |
| 1459 |
underscore to not clash with exported function names: |
| 1460 |
|
| 1461 |
|
| 1462 |
.. attribute:: PyDLL._handle |
| 1463 |
|
| 1464 |
The system handle used to access the library. |
| 1465 |
|
| 1466 |
|
| 1467 |
.. attribute:: PyDLL._name |
| 1468 |
|
| 1469 |
The name of the library passed in the constructor. |
| 1470 |
|
| 1471 |
Shared libraries can also be loaded by using one of the prefabricated objects, |
| 1472 |
which are instances of the :class:`LibraryLoader` class, either by calling the |
| 1473 |
:meth:`LoadLibrary` method, or by retrieving the library as attribute of the |
| 1474 |
loader instance. |
| 1475 |
|
| 1476 |
|
| 1477 |
.. class:: LibraryLoader(dlltype) |
| 1478 |
|
| 1479 |
Class which loads shared libraries. *dlltype* should be one of the |
| 1480 |
:class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types. |
| 1481 |
|
| 1482 |
:meth:`__getattr__` has special behavior: It allows loading a shared library by |
| 1483 |
accessing it as attribute of a library loader instance. The result is cached, |
| 1484 |
so repeated attribute accesses return the same library each time. |
| 1485 |
|
| 1486 |
|
| 1487 |
.. method:: LoadLibrary(name) |
| 1488 |
|
| 1489 |
Load a shared library into the process and return it. This method always |
| 1490 |
returns a new instance of the library. |
| 1491 |
|
| 1492 |
These prefabricated library loaders are available: |
| 1493 |
|
| 1494 |
|
| 1495 |
.. data:: cdll |
| 1496 |
:noindex: |
| 1497 |
|
| 1498 |
Creates :class:`CDLL` instances. |
| 1499 |
|
| 1500 |
|
| 1501 |
.. data:: windll |
| 1502 |
:noindex: |
| 1503 |
|
| 1504 |
Windows only: Creates :class:`WinDLL` instances. |
| 1505 |
|
| 1506 |
|
| 1507 |
.. data:: oledll |
| 1508 |
:noindex: |
| 1509 |
|
| 1510 |
Windows only: Creates :class:`OleDLL` instances. |
| 1511 |
|
| 1512 |
|
| 1513 |
.. data:: pydll |
| 1514 |
:noindex: |
| 1515 |
|
| 1516 |
Creates :class:`PyDLL` instances. |
| 1517 |
|
| 1518 |
For accessing the C Python api directly, a ready-to-use Python shared library |
| 1519 |
object is available: |
| 1520 |
|
| 1521 |
|
| 1522 |
.. data:: pythonapi |
| 1523 |
:noindex: |
| 1524 |
|
| 1525 |
An instance of :class:`PyDLL` that exposes Python C API functions as |
| 1526 |
attributes. Note that all these functions are assumed to return C |
| 1527 |
:c:type:`int`, which is of course not always the truth, so you have to assign |
| 1528 |
the correct :attr:`restype` attribute to use these functions. |
| 1529 |
|
| 1530 |
|
| 1531 |
.. _ctypes-foreign-functions: |
| 1532 |
|
| 1533 |
Foreign functions |
| 1534 |
^^^^^^^^^^^^^^^^^ |
| 1535 |
|
| 1536 |
As explained in the previous section, foreign functions can be accessed as |
| 1537 |
attributes of loaded shared libraries. The function objects created in this way |
| 1538 |
by default accept any number of arguments, accept any ctypes data instances as |
| 1539 |
arguments, and return the default result type specified by the library loader. |
| 1540 |
They are instances of a private class: |
| 1541 |
|
| 1542 |
|
| 1543 |
.. class:: _FuncPtr |
| 1544 |
|
| 1545 |
Base class for C callable foreign functions. |
| 1546 |
|
| 1547 |
Instances of foreign functions are also C compatible data types; they |
| 1548 |
represent C function pointers. |
| 1549 |
|
| 1550 |
This behavior can be customized by assigning to special attributes of the |
| 1551 |
foreign function object. |
| 1552 |
|
| 1553 |
|
| 1554 |
.. attribute:: restype |
| 1555 |
|
| 1556 |
Assign a ctypes type to specify the result type of the foreign function. |
| 1557 |
Use ``None`` for :c:type:`void`, a function not returning anything. |
| 1558 |
|
| 1559 |
It is possible to assign a callable Python object that is not a ctypes |
| 1560 |
type, in this case the function is assumed to return a C :c:type:`int`, and |
| 1561 |
the callable will be called with this integer, allowing further |
| 1562 |
processing or error checking. Using this is deprecated, for more flexible |
| 1563 |
post processing or error checking use a ctypes data type as |
| 1564 |
:attr:`restype` and assign a callable to the :attr:`errcheck` attribute. |
| 1565 |
|
| 1566 |
|
| 1567 |
.. attribute:: argtypes |
| 1568 |
|
| 1569 |
Assign a tuple of ctypes types to specify the argument types that the |
| 1570 |
function accepts. Functions using the ``stdcall`` calling convention can |
| 1571 |
only be called with the same number of arguments as the length of this |
| 1572 |
tuple; functions using the C calling convention accept additional, |
| 1573 |
unspecified arguments as well. |
| 1574 |
|
| 1575 |
When a foreign function is called, each actual argument is passed to the |
| 1576 |
:meth:`from_param` class method of the items in the :attr:`argtypes` |
| 1577 |
tuple, this method allows adapting the actual argument to an object that |
| 1578 |
the foreign function accepts. For example, a :class:`c_char_p` item in |
| 1579 |
the :attr:`argtypes` tuple will convert a unicode string passed as |
| 1580 |
argument into a byte string using ctypes conversion rules. |
| 1581 |
|
| 1582 |
New: It is now possible to put items in argtypes which are not ctypes |
| 1583 |
types, but each item must have a :meth:`from_param` method which returns a |
| 1584 |
value usable as argument (integer, string, ctypes instance). This allows |
| 1585 |
defining adapters that can adapt custom objects as function parameters. |
| 1586 |
|
| 1587 |
|
| 1588 |
.. attribute:: errcheck |
| 1589 |
|
| 1590 |
Assign a Python function or another callable to this attribute. The |
| 1591 |
callable will be called with three or more arguments: |
| 1592 |
|
| 1593 |
.. function:: callable(result, func, arguments) |
| 1594 |
:noindex: |
| 1595 |
|
| 1596 |
*result* is what the foreign function returns, as specified by the |
| 1597 |
:attr:`restype` attribute. |
| 1598 |
|
| 1599 |
*func* is the foreign function object itself, this allows reusing the |
| 1600 |
same callable object to check or post process the results of several |
| 1601 |
functions. |
| 1602 |
|
| 1603 |
*arguments* is a tuple containing the parameters originally passed to |
| 1604 |
the function call, this allows specializing the behavior on the |
| 1605 |
arguments used. |
| 1606 |
|
| 1607 |
The object that this function returns will be returned from the |
| 1608 |
foreign function call, but it can also check the result value |
| 1609 |
and raise an exception if the foreign function call failed. |
| 1610 |
|
| 1611 |
|
| 1612 |
.. exception:: ArgumentError() |
| 1613 |
|
| 1614 |
This exception is raised when a foreign function call cannot convert one of the |
| 1615 |
passed arguments. |
| 1616 |
|
| 1617 |
|
| 1618 |
.. _ctypes-function-prototypes: |
| 1619 |
|
| 1620 |
Function prototypes |
| 1621 |
^^^^^^^^^^^^^^^^^^^ |
| 1622 |
|
| 1623 |
Foreign functions can also be created by instantiating function prototypes. |
| 1624 |
Function prototypes are similar to function prototypes in C; they describe a |
| 1625 |
function (return type, argument types, calling convention) without defining an |
| 1626 |
implementation. The factory functions must be called with the desired result |
| 1627 |
type and the argument types of the function. |
| 1628 |
|
| 1629 |
|
| 1630 |
.. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False) |
| 1631 |
|
| 1632 |
The returned function prototype creates functions that use the standard C |
| 1633 |
calling convention. The function will release the GIL during the call. If |
| 1634 |
*use_errno* is set to true, the ctypes private copy of the system |
| 1635 |
:data:`errno` variable is exchanged with the real :data:`errno` value before |
| 1636 |
and after the call; *use_last_error* does the same for the Windows error |
| 1637 |
code. |
| 1638 |
|
| 1639 |
.. versionchanged:: 2.6 |
| 1640 |
The optional *use_errno* and *use_last_error* parameters were added. |
| 1641 |
|
| 1642 |
|
| 1643 |
.. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False) |
| 1644 |
|
| 1645 |
Windows only: The returned function prototype creates functions that use the |
| 1646 |
``stdcall`` calling convention, except on Windows CE where |
| 1647 |
:func:`WINFUNCTYPE` is the same as :func:`CFUNCTYPE`. The function will |
| 1648 |
release the GIL during the call. *use_errno* and *use_last_error* have the |
| 1649 |
same meaning as above. |
| 1650 |
|
| 1651 |
|
| 1652 |
.. function:: PYFUNCTYPE(restype, *argtypes) |
| 1653 |
|
| 1654 |
The returned function prototype creates functions that use the Python calling |
| 1655 |
convention. The function will *not* release the GIL during the call. |
| 1656 |
|
| 1657 |
Function prototypes created by these factory functions can be instantiated in |
| 1658 |
different ways, depending on the type and number of the parameters in the call: |
| 1659 |
|
| 1660 |
|
| 1661 |
.. function:: prototype(address) |
| 1662 |
:noindex: |
| 1663 |
:module: |
| 1664 |
|
| 1665 |
Returns a foreign function at the specified address which must be an integer. |
| 1666 |
|
| 1667 |
|
| 1668 |
.. function:: prototype(callable) |
| 1669 |
:noindex: |
| 1670 |
:module: |
| 1671 |
|
| 1672 |
Create a C callable function (a callback function) from a Python *callable*. |
| 1673 |
|
| 1674 |
|
| 1675 |
.. function:: prototype(func_spec[, paramflags]) |
| 1676 |
:noindex: |
| 1677 |
:module: |
| 1678 |
|
| 1679 |
Returns a foreign function exported by a shared library. *func_spec* must be a |
| 1680 |
2-tuple ``(name_or_ordinal, library)``. The first item is the name of the |
| 1681 |
exported function as string, or the ordinal of the exported function as small |
| 1682 |
integer. The second item is the shared library instance. |
| 1683 |
|
| 1684 |
|
| 1685 |
.. function:: prototype(vtbl_index, name[, paramflags[, iid]]) |
| 1686 |
:noindex: |
| 1687 |
:module: |
| 1688 |
|
| 1689 |
Returns a foreign function that will call a COM method. *vtbl_index* is the |
| 1690 |
index into the virtual function table, a small non-negative integer. *name* is |
| 1691 |
name of the COM method. *iid* is an optional pointer to the interface identifier |
| 1692 |
which is used in extended error reporting. |
| 1693 |
|
| 1694 |
COM methods use a special calling convention: They require a pointer to the COM |
| 1695 |
interface as first argument, in addition to those parameters that are specified |
| 1696 |
in the :attr:`argtypes` tuple. |
| 1697 |
|
| 1698 |
The optional *paramflags* parameter creates foreign function wrappers with much |
| 1699 |
more functionality than the features described above. |
| 1700 |
|
| 1701 |
*paramflags* must be a tuple of the same length as :attr:`argtypes`. |
| 1702 |
|
| 1703 |
Each item in this tuple contains further information about a parameter, it must |
| 1704 |
be a tuple containing one, two, or three items. |
| 1705 |
|
| 1706 |
The first item is an integer containing a combination of direction |
| 1707 |
flags for the parameter: |
| 1708 |
|
| 1709 |
1 |
| 1710 |
Specifies an input parameter to the function. |
| 1711 |
|
| 1712 |
2 |
| 1713 |
Output parameter. The foreign function fills in a value. |
| 1714 |
|
| 1715 |
4 |
| 1716 |
Input parameter which defaults to the integer zero. |
| 1717 |
|
| 1718 |
The optional second item is the parameter name as string. If this is specified, |
| 1719 |
the foreign function can be called with named parameters. |
| 1720 |
|
| 1721 |
The optional third item is the default value for this parameter. |
| 1722 |
|
| 1723 |
This example demonstrates how to wrap the Windows ``MessageBoxA`` function so |
| 1724 |
that it supports default parameters and named arguments. The C declaration from |
| 1725 |
the windows header file is this:: |
| 1726 |
|
| 1727 |
WINUSERAPI int WINAPI |
| 1728 |
MessageBoxA( |
| 1729 |
HWND hWnd, |
| 1730 |
LPCSTR lpText, |
| 1731 |
LPCSTR lpCaption, |
| 1732 |
UINT uType); |
| 1733 |
|
| 1734 |
Here is the wrapping with :mod:`ctypes`:: |
| 1735 |
|
| 1736 |
>>> from ctypes import c_int, WINFUNCTYPE, windll |
| 1737 |
>>> from ctypes.wintypes import HWND, LPCSTR, UINT |
| 1738 |
>>> prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT) |
| 1739 |
>>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0) |
| 1740 |
>>> MessageBox = prototype(("MessageBoxA", windll.user32), paramflags) |
| 1741 |
>>> |
| 1742 |
|
| 1743 |
The MessageBox foreign function can now be called in these ways:: |
| 1744 |
|
| 1745 |
>>> MessageBox() |
| 1746 |
>>> MessageBox(text="Spam, spam, spam") |
| 1747 |
>>> MessageBox(flags=2, text="foo bar") |
| 1748 |
>>> |
| 1749 |
|
| 1750 |
A second example demonstrates output parameters. The win32 ``GetWindowRect`` |
| 1751 |
function retrieves the dimensions of a specified window by copying them into |
| 1752 |
``RECT`` structure that the caller has to supply. Here is the C declaration:: |
| 1753 |
|
| 1754 |
WINUSERAPI BOOL WINAPI |
| 1755 |
GetWindowRect( |
| 1756 |
HWND hWnd, |
| 1757 |
LPRECT lpRect); |
| 1758 |
|
| 1759 |
Here is the wrapping with :mod:`ctypes`:: |
| 1760 |
|
| 1761 |
>>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError |
| 1762 |
>>> from ctypes.wintypes import BOOL, HWND, RECT |
| 1763 |
>>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT)) |
| 1764 |
>>> paramflags = (1, "hwnd"), (2, "lprect") |
| 1765 |
>>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags) |
| 1766 |
>>> |
| 1767 |
|
| 1768 |
Functions with output parameters will automatically return the output parameter |
| 1769 |
value if there is a single one, or a tuple containing the output parameter |
| 1770 |
values when there are more than one, so the GetWindowRect function now returns a |
| 1771 |
RECT instance, when called. |
| 1772 |
|
| 1773 |
Output parameters can be combined with the :attr:`errcheck` protocol to do |
| 1774 |
further output processing and error checking. The win32 ``GetWindowRect`` api |
| 1775 |
function returns a ``BOOL`` to signal success or failure, so this function could |
| 1776 |
do the error checking, and raises an exception when the api call failed:: |
| 1777 |
|
| 1778 |
>>> def errcheck(result, func, args): |
| 1779 |
... if not result: |
| 1780 |
... raise WinError() |
| 1781 |
... return args |
| 1782 |
... |
| 1783 |
>>> GetWindowRect.errcheck = errcheck |
| 1784 |
>>> |
| 1785 |
|
| 1786 |
If the :attr:`errcheck` function returns the argument tuple it receives |
| 1787 |
unchanged, :mod:`ctypes` continues the normal processing it does on the output |
| 1788 |
parameters. If you want to return a tuple of window coordinates instead of a |
| 1789 |
``RECT`` instance, you can retrieve the fields in the function and return them |
| 1790 |
instead, the normal processing will no longer take place:: |
| 1791 |
|
| 1792 |
>>> def errcheck(result, func, args): |
| 1793 |
... if not result: |
| 1794 |
... raise WinError() |
| 1795 |
... rc = args[1] |
| 1796 |
... return rc.left, rc.top, rc.bottom, rc.right |
| 1797 |
... |
| 1798 |
>>> GetWindowRect.errcheck = errcheck |
| 1799 |
>>> |
| 1800 |
|
| 1801 |
|
| 1802 |
.. _ctypes-utility-functions: |
| 1803 |
|
| 1804 |
Utility functions |
| 1805 |
^^^^^^^^^^^^^^^^^ |
| 1806 |
|
| 1807 |
|
| 1808 |
.. function:: addressof(obj) |
| 1809 |
|
| 1810 |
Returns the address of the memory buffer as integer. *obj* must be an |
| 1811 |
instance of a ctypes type. |
| 1812 |
|
| 1813 |
|
| 1814 |
.. function:: alignment(obj_or_type) |
| 1815 |
|
| 1816 |
Returns the alignment requirements of a ctypes type. *obj_or_type* must be a |
| 1817 |
ctypes type or instance. |
| 1818 |
|
| 1819 |
|
| 1820 |
.. function:: byref(obj[, offset]) |
| 1821 |
|
| 1822 |
Returns a light-weight pointer to *obj*, which must be an instance of a |
| 1823 |
ctypes type. *offset* defaults to zero, and must be an integer that will be |
| 1824 |
added to the internal pointer value. |
| 1825 |
|
| 1826 |
``byref(obj, offset)`` corresponds to this C code:: |
| 1827 |
|
| 1828 |
(((char *)&obj) + offset) |
| 1829 |
|
| 1830 |
The returned object can only be used as a foreign function call |
| 1831 |
parameter. It behaves similar to ``pointer(obj)``, but the |
| 1832 |
construction is a lot faster. |
| 1833 |
|
| 1834 |
.. versionadded:: 2.6 |
| 1835 |
The *offset* optional argument was added. |
| 1836 |
|
| 1837 |
|
| 1838 |
.. function:: cast(obj, type) |
| 1839 |
|
| 1840 |
This function is similar to the cast operator in C. It returns a new |
| 1841 |
instance of *type* which points to the same memory block as *obj*. *type* |
| 1842 |
must be a pointer type, and *obj* must be an object that can be interpreted |
| 1843 |
as a pointer. |
| 1844 |
|
| 1845 |
|
| 1846 |
.. function:: create_string_buffer(init_or_size[, size]) |
| 1847 |
|
| 1848 |
This function creates a mutable character buffer. The returned object is a |
| 1849 |
ctypes array of :class:`c_char`. |
| 1850 |
|
| 1851 |
*init_or_size* must be an integer which specifies the size of the array, or a |
| 1852 |
string which will be used to initialize the array items. |
| 1853 |
|
| 1854 |
If a string is specified as first argument, the buffer is made one item larger |
| 1855 |
than the length of the string so that the last element in the array is a NUL |
| 1856 |
termination character. An integer can be passed as second argument which allows |
| 1857 |
specifying the size of the array if the length of the string should not be used. |
| 1858 |
|
| 1859 |
If the first parameter is a unicode string, it is converted into an 8-bit string |
| 1860 |
according to ctypes conversion rules. |
| 1861 |
|
| 1862 |
|
| 1863 |
.. function:: create_unicode_buffer(init_or_size[, size]) |
| 1864 |
|
| 1865 |
This function creates a mutable unicode character buffer. The returned object is |
| 1866 |
a ctypes array of :class:`c_wchar`. |
| 1867 |
|
| 1868 |
*init_or_size* must be an integer which specifies the size of the array, or a |
| 1869 |
unicode string which will be used to initialize the array items. |
| 1870 |
|
| 1871 |
If a unicode string is specified as first argument, the buffer is made one item |
| 1872 |
larger than the length of the string so that the last element in the array is a |
| 1873 |
NUL termination character. An integer can be passed as second argument which |
| 1874 |
allows specifying the size of the array if the length of the string should not |
| 1875 |
be used. |
| 1876 |
|
| 1877 |
If the first parameter is an 8-bit string, it is converted into a unicode string |
| 1878 |
according to ctypes conversion rules. |
| 1879 |
|
| 1880 |
|
| 1881 |
.. function:: DllCanUnloadNow() |
| 1882 |
|
| 1883 |
Windows only: This function is a hook which allows implementing in-process |
| 1884 |
COM servers with ctypes. It is called from the DllCanUnloadNow function that |
| 1885 |
the _ctypes extension dll exports. |
| 1886 |
|
| 1887 |
|
| 1888 |
.. function:: DllGetClassObject() |
| 1889 |
|
| 1890 |
Windows only: This function is a hook which allows implementing in-process |
| 1891 |
COM servers with ctypes. It is called from the DllGetClassObject function |
| 1892 |
that the ``_ctypes`` extension dll exports. |
| 1893 |
|
| 1894 |
|
| 1895 |
.. function:: find_library(name) |
| 1896 |
:module: ctypes.util |
| 1897 |
|
| 1898 |
Try to find a library and return a pathname. *name* is the library name |
| 1899 |
without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version |
| 1900 |
number (this is the form used for the posix linker option :option:`!-l`). If |
| 1901 |
no library can be found, returns ``None``. |
| 1902 |
|
| 1903 |
The exact functionality is system dependent. |
| 1904 |
|
| 1905 |
.. versionchanged:: 2.6 |
| 1906 |
Windows only: ``find_library("m")`` or ``find_library("c")`` return the |
| 1907 |
result of a call to ``find_msvcrt()``. |
| 1908 |
|
| 1909 |
|
| 1910 |
.. function:: find_msvcrt() |
| 1911 |
:module: ctypes.util |
| 1912 |
|
| 1913 |
Windows only: return the filename of the VC runtime library used by Python, |
| 1914 |
and by the extension modules. If the name of the library cannot be |
| 1915 |
determined, ``None`` is returned. |
| 1916 |
|
| 1917 |
If you need to free memory, for example, allocated by an extension module |
| 1918 |
with a call to the ``free(void *)``, it is important that you use the |
| 1919 |
function in the same library that allocated the memory. |
| 1920 |
|
| 1921 |
.. versionadded:: 2.6 |
| 1922 |
|
| 1923 |
|
| 1924 |
.. function:: FormatError([code]) |
| 1925 |
|
| 1926 |
Windows only: Returns a textual description of the error code *code*. If no |
| 1927 |
error code is specified, the last error code is used by calling the Windows |
| 1928 |
api function GetLastError. |
| 1929 |
|
| 1930 |
|
| 1931 |
.. function:: GetLastError() |
| 1932 |
|
| 1933 |
Windows only: Returns the last error code set by Windows in the calling thread. |
| 1934 |
This function calls the Windows `GetLastError()` function directly, |
| 1935 |
it does not return the ctypes-private copy of the error code. |
| 1936 |
|
| 1937 |
.. function:: get_errno() |
| 1938 |
|
| 1939 |
Returns the current value of the ctypes-private copy of the system |
| 1940 |
:data:`errno` variable in the calling thread. |
| 1941 |
|
| 1942 |
.. versionadded:: 2.6 |
| 1943 |
|
| 1944 |
.. function:: get_last_error() |
| 1945 |
|
| 1946 |
Windows only: returns the current value of the ctypes-private copy of the system |
| 1947 |
:data:`LastError` variable in the calling thread. |
| 1948 |
|
| 1949 |
.. versionadded:: 2.6 |
| 1950 |
|
| 1951 |
.. function:: memmove(dst, src, count) |
| 1952 |
|
| 1953 |
Same as the standard C memmove library function: copies *count* bytes from |
| 1954 |
*src* to *dst*. *dst* and *src* must be integers or ctypes instances that can |
| 1955 |
be converted to pointers. |
| 1956 |
|
| 1957 |
|
| 1958 |
.. function:: memset(dst, c, count) |
| 1959 |
|
| 1960 |
Same as the standard C memset library function: fills the memory block at |
| 1961 |
address *dst* with *count* bytes of value *c*. *dst* must be an integer |
| 1962 |
specifying an address, or a ctypes instance. |
| 1963 |
|
| 1964 |
|
| 1965 |
.. function:: POINTER(type) |
| 1966 |
|
| 1967 |
This factory function creates and returns a new ctypes pointer type. Pointer |
| 1968 |
types are cached and reused internally, so calling this function repeatedly is |
| 1969 |
cheap. *type* must be a ctypes type. |
| 1970 |
|
| 1971 |
|
| 1972 |
.. function:: pointer(obj) |
| 1973 |
|
| 1974 |
This function creates a new pointer instance, pointing to *obj*. The returned |
| 1975 |
object is of the type ``POINTER(type(obj))``. |
| 1976 |
|
| 1977 |
Note: If you just want to pass a pointer to an object to a foreign function |
| 1978 |
call, you should use ``byref(obj)`` which is much faster. |
| 1979 |
|
| 1980 |
|
| 1981 |
.. function:: resize(obj, size) |
| 1982 |
|
| 1983 |
This function resizes the internal memory buffer of *obj*, which must be an |
| 1984 |
instance of a ctypes type. It is not possible to make the buffer smaller |
| 1985 |
than the native size of the objects type, as given by ``sizeof(type(obj))``, |
| 1986 |
but it is possible to enlarge the buffer. |
| 1987 |
|
| 1988 |
|
| 1989 |
.. function:: set_conversion_mode(encoding, errors) |
| 1990 |
|
| 1991 |
This function sets the rules that ctypes objects use when converting between |
| 1992 |
8-bit strings and unicode strings. *encoding* must be a string specifying an |
| 1993 |
encoding, like ``'utf-8'`` or ``'mbcs'``, *errors* must be a string |
| 1994 |
specifying the error handling on encoding/decoding errors. Examples of |
| 1995 |
possible values are ``"strict"``, ``"replace"``, or ``"ignore"``. |
| 1996 |
|
| 1997 |
:func:`set_conversion_mode` returns a 2-tuple containing the previous |
| 1998 |
conversion rules. On windows, the initial conversion rules are ``('mbcs', |
| 1999 |
'ignore')``, on other systems ``('ascii', 'strict')``. |
| 2000 |
|
| 2001 |
|
| 2002 |
.. function:: set_errno(value) |
| 2003 |
|
| 2004 |
Set the current value of the ctypes-private copy of the system :data:`errno` |
| 2005 |
variable in the calling thread to *value* and return the previous value. |
| 2006 |
|
| 2007 |
.. versionadded:: 2.6 |
| 2008 |
|
| 2009 |
|
| 2010 |
.. function:: set_last_error(value) |
| 2011 |
|
| 2012 |
Windows only: set the current value of the ctypes-private copy of the system |
| 2013 |
:data:`LastError` variable in the calling thread to *value* and return the |
| 2014 |
previous value. |
| 2015 |
|
| 2016 |
.. versionadded:: 2.6 |
| 2017 |
|
| 2018 |
|
| 2019 |
.. function:: sizeof(obj_or_type) |
| 2020 |
|
| 2021 |
Returns the size in bytes of a ctypes type or instance memory buffer. |
| 2022 |
Does the same as the C ``sizeof`` operator. |
| 2023 |
|
| 2024 |
|
| 2025 |
.. function:: string_at(address[, size]) |
| 2026 |
|
| 2027 |
This function returns the string starting at memory address *address*. If size |
| 2028 |
is specified, it is used as size, otherwise the string is assumed to be |
| 2029 |
zero-terminated. |
| 2030 |
|
| 2031 |
|
| 2032 |
.. function:: WinError(code=None, descr=None) |
| 2033 |
|
| 2034 |
Windows only: this function is probably the worst-named thing in ctypes. It |
| 2035 |
creates an instance of WindowsError. If *code* is not specified, |
| 2036 |
``GetLastError`` is called to determine the error code. If ``descr`` is not |
| 2037 |
specified, :func:`FormatError` is called to get a textual description of the |
| 2038 |
error. |
| 2039 |
|
| 2040 |
|
| 2041 |
.. function:: wstring_at(address[, size]) |
| 2042 |
|
| 2043 |
This function returns the wide character string starting at memory address |
| 2044 |
*address* as unicode string. If *size* is specified, it is used as the |
| 2045 |
number of characters of the string, otherwise the string is assumed to be |
| 2046 |
zero-terminated. |
| 2047 |
|
| 2048 |
|
| 2049 |
.. _ctypes-data-types: |
| 2050 |
|
| 2051 |
Data types |
| 2052 |
^^^^^^^^^^ |
| 2053 |
|
| 2054 |
|
| 2055 |
.. class:: _CData |
| 2056 |
|
| 2057 |
This non-public class is the common base class of all ctypes data types. |
| 2058 |
Among other things, all ctypes type instances contain a memory block that |
| 2059 |
hold C compatible data; the address of the memory block is returned by the |
| 2060 |
:func:`addressof` helper function. Another instance variable is exposed as |
| 2061 |
:attr:`_objects`; this contains other Python objects that need to be kept |
| 2062 |
alive in case the memory block contains pointers. |
| 2063 |
|
| 2064 |
Common methods of ctypes data types, these are all class methods (to be |
| 2065 |
exact, they are methods of the :term:`metaclass`): |
| 2066 |
|
| 2067 |
|
| 2068 |
.. method:: _CData.from_buffer(source[, offset]) |
| 2069 |
|
| 2070 |
This method returns a ctypes instance that shares the buffer of the |
| 2071 |
*source* object. The *source* object must support the writeable buffer |
| 2072 |
interface. The optional *offset* parameter specifies an offset into the |
| 2073 |
source buffer in bytes; the default is zero. If the source buffer is not |
| 2074 |
large enough a :exc:`ValueError` is raised. |
| 2075 |
|
| 2076 |
.. versionadded:: 2.6 |
| 2077 |
|
| 2078 |
|
| 2079 |
.. method:: _CData.from_buffer_copy(source[, offset]) |
| 2080 |
|
| 2081 |
This method creates a ctypes instance, copying the buffer from the |
| 2082 |
*source* object buffer which must be readable. The optional *offset* |
| 2083 |
parameter specifies an offset into the source buffer in bytes; the default |
| 2084 |
is zero. If the source buffer is not large enough a :exc:`ValueError` is |
| 2085 |
raised. |
| 2086 |
|
| 2087 |
.. versionadded:: 2.6 |
| 2088 |
|
| 2089 |
|
| 2090 |
.. method:: from_address(address) |
| 2091 |
|
| 2092 |
This method returns a ctypes type instance using the memory specified by |
| 2093 |
*address* which must be an integer. |
| 2094 |
|
| 2095 |
|
| 2096 |
.. method:: from_param(obj) |
| 2097 |
|
| 2098 |
This method adapts *obj* to a ctypes type. It is called with the actual |
| 2099 |
object used in a foreign function call when the type is present in the |
| 2100 |
foreign function's :attr:`argtypes` tuple; it must return an object that |
| 2101 |
can be used as a function call parameter. |
| 2102 |
|
| 2103 |
All ctypes data types have a default implementation of this classmethod |
| 2104 |
that normally returns *obj* if that is an instance of the type. Some |
| 2105 |
types accept other objects as well. |
| 2106 |
|
| 2107 |
|
| 2108 |
.. method:: in_dll(library, name) |
| 2109 |
|
| 2110 |
This method returns a ctypes type instance exported by a shared |
| 2111 |
library. *name* is the name of the symbol that exports the data, *library* |
| 2112 |
is the loaded shared library. |
| 2113 |
|
| 2114 |
|
| 2115 |
Common instance variables of ctypes data types: |
| 2116 |
|
| 2117 |
.. attribute:: _b_base_ |
| 2118 |
|
| 2119 |
Sometimes ctypes data instances do not own the memory block they contain, |
| 2120 |
instead they share part of the memory block of a base object. The |
| 2121 |
:attr:`_b_base_` read-only member is the root ctypes object that owns the |
| 2122 |
memory block. |
| 2123 |
|
| 2124 |
|
| 2125 |
.. attribute:: _b_needsfree_ |
| 2126 |
|
| 2127 |
This read-only variable is true when the ctypes data instance has |
| 2128 |
allocated the memory block itself, false otherwise. |
| 2129 |
|
| 2130 |
|
| 2131 |
.. attribute:: _objects |
| 2132 |
|
| 2133 |
This member is either ``None`` or a dictionary containing Python objects |
| 2134 |
that need to be kept alive so that the memory block contents is kept |
| 2135 |
valid. This object is only exposed for debugging; never modify the |
| 2136 |
contents of this dictionary. |
| 2137 |
|
| 2138 |
|
| 2139 |
.. _ctypes-fundamental-data-types-2: |
| 2140 |
|
| 2141 |
Fundamental data types |
| 2142 |
^^^^^^^^^^^^^^^^^^^^^^ |
| 2143 |
|
| 2144 |
|
| 2145 |
.. class:: _SimpleCData |
| 2146 |
|
| 2147 |
This non-public class is the base class of all fundamental ctypes data |
| 2148 |
types. It is mentioned here because it contains the common attributes of the |
| 2149 |
fundamental ctypes data types. :class:`_SimpleCData` is a subclass of |
| 2150 |
:class:`_CData`, so it inherits their methods and attributes. |
| 2151 |
|
| 2152 |
.. versionchanged:: 2.6 |
| 2153 |
ctypes data types that are not and do not contain pointers can now be |
| 2154 |
pickled. |
| 2155 |
|
| 2156 |
Instances have a single attribute: |
| 2157 |
|
| 2158 |
.. attribute:: value |
| 2159 |
|
| 2160 |
This attribute contains the actual value of the instance. For integer and |
| 2161 |
pointer types, it is an integer, for character types, it is a single |
| 2162 |
character string, for character pointer types it is a Python string or |
| 2163 |
unicode string. |
| 2164 |
|
| 2165 |
When the ``value`` attribute is retrieved from a ctypes instance, usually |
| 2166 |
a new object is returned each time. :mod:`ctypes` does *not* implement |
| 2167 |
original object return, always a new object is constructed. The same is |
| 2168 |
true for all other ctypes object instances. |
| 2169 |
|
| 2170 |
|
| 2171 |
Fundamental data types, when returned as foreign function call results, or, for |
| 2172 |
example, by retrieving structure field members or array items, are transparently |
| 2173 |
converted to native Python types. In other words, if a foreign function has a |
| 2174 |
:attr:`restype` of :class:`c_char_p`, you will always receive a Python string, |
| 2175 |
*not* a :class:`c_char_p` instance. |
| 2176 |
|
| 2177 |
Subclasses of fundamental data types do *not* inherit this behavior. So, if a |
| 2178 |
foreign functions :attr:`restype` is a subclass of :class:`c_void_p`, you will |
| 2179 |
receive an instance of this subclass from the function call. Of course, you can |
| 2180 |
get the value of the pointer by accessing the ``value`` attribute. |
| 2181 |
|
| 2182 |
These are the fundamental ctypes data types: |
| 2183 |
|
| 2184 |
.. class:: c_byte |
| 2185 |
|
| 2186 |
Represents the C :c:type:`signed char` datatype, and interprets the value as |
| 2187 |
small integer. The constructor accepts an optional integer initializer; no |
| 2188 |
overflow checking is done. |
| 2189 |
|
| 2190 |
|
| 2191 |
.. class:: c_char |
| 2192 |
|
| 2193 |
Represents the C :c:type:`char` datatype, and interprets the value as a single |
| 2194 |
character. The constructor accepts an optional string initializer, the |
| 2195 |
length of the string must be exactly one character. |
| 2196 |
|
| 2197 |
|
| 2198 |
.. class:: c_char_p |
| 2199 |
|
| 2200 |
Represents the C :c:type:`char *` datatype when it points to a zero-terminated |
| 2201 |
string. For a general character pointer that may also point to binary data, |
| 2202 |
``POINTER(c_char)`` must be used. The constructor accepts an integer |
| 2203 |
address, or a string. |
| 2204 |
|
| 2205 |
|
| 2206 |
.. class:: c_double |
| 2207 |
|
| 2208 |
Represents the C :c:type:`double` datatype. The constructor accepts an |
| 2209 |
optional float initializer. |
| 2210 |
|
| 2211 |
|
| 2212 |
.. class:: c_longdouble |
| 2213 |
|
| 2214 |
Represents the C :c:type:`long double` datatype. The constructor accepts an |
| 2215 |
optional float initializer. On platforms where ``sizeof(long double) == |
| 2216 |
sizeof(double)`` it is an alias to :class:`c_double`. |
| 2217 |
|
| 2218 |
.. versionadded:: 2.6 |
| 2219 |
|
| 2220 |
.. class:: c_float |
| 2221 |
|
| 2222 |
Represents the C :c:type:`float` datatype. The constructor accepts an |
| 2223 |
optional float initializer. |
| 2224 |
|
| 2225 |
|
| 2226 |
.. class:: c_int |
| 2227 |
|
| 2228 |
Represents the C :c:type:`signed int` datatype. The constructor accepts an |
| 2229 |
optional integer initializer; no overflow checking is done. On platforms |
| 2230 |
where ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`. |
| 2231 |
|
| 2232 |
|
| 2233 |
.. class:: c_int8 |
| 2234 |
|
| 2235 |
Represents the C 8-bit :c:type:`signed int` datatype. Usually an alias for |
| 2236 |
:class:`c_byte`. |
| 2237 |
|
| 2238 |
|
| 2239 |
.. class:: c_int16 |
| 2240 |
|
| 2241 |
Represents the C 16-bit :c:type:`signed int` datatype. Usually an alias for |
| 2242 |
:class:`c_short`. |
| 2243 |
|
| 2244 |
|
| 2245 |
.. class:: c_int32 |
| 2246 |
|
| 2247 |
Represents the C 32-bit :c:type:`signed int` datatype. Usually an alias for |
| 2248 |
:class:`c_int`. |
| 2249 |
|
| 2250 |
|
| 2251 |
.. class:: c_int64 |
| 2252 |
|
| 2253 |
Represents the C 64-bit :c:type:`signed int` datatype. Usually an alias for |
| 2254 |
:class:`c_longlong`. |
| 2255 |
|
| 2256 |
|
| 2257 |
.. class:: c_long |
| 2258 |
|
| 2259 |
Represents the C :c:type:`signed long` datatype. The constructor accepts an |
| 2260 |
optional integer initializer; no overflow checking is done. |
| 2261 |
|
| 2262 |
|
| 2263 |
.. class:: c_longlong |
| 2264 |
|
| 2265 |
Represents the C :c:type:`signed long long` datatype. The constructor accepts |
| 2266 |
an optional integer initializer; no overflow checking is done. |
| 2267 |
|
| 2268 |
|
| 2269 |
.. class:: c_short |
| 2270 |
|
| 2271 |
Represents the C :c:type:`signed short` datatype. The constructor accepts an |
| 2272 |
optional integer initializer; no overflow checking is done. |
| 2273 |
|
| 2274 |
|
| 2275 |
.. class:: c_size_t |
| 2276 |
|
| 2277 |
Represents the C :c:type:`size_t` datatype. |
| 2278 |
|
| 2279 |
|
| 2280 |
.. class:: c_ssize_t |
| 2281 |
|
| 2282 |
Represents the C :c:type:`ssize_t` datatype. |
| 2283 |
|
| 2284 |
.. versionadded:: 2.7 |
| 2285 |
|
| 2286 |
|
| 2287 |
.. class:: c_ubyte |
| 2288 |
|
| 2289 |
Represents the C :c:type:`unsigned char` datatype, it interprets the value as |
| 2290 |
small integer. The constructor accepts an optional integer initializer; no |
| 2291 |
overflow checking is done. |
| 2292 |
|
| 2293 |
|
| 2294 |
.. class:: c_uint |
| 2295 |
|
| 2296 |
Represents the C :c:type:`unsigned int` datatype. The constructor accepts an |
| 2297 |
optional integer initializer; no overflow checking is done. On platforms |
| 2298 |
where ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`. |
| 2299 |
|
| 2300 |
|
| 2301 |
.. class:: c_uint8 |
| 2302 |
|
| 2303 |
Represents the C 8-bit :c:type:`unsigned int` datatype. Usually an alias for |
| 2304 |
:class:`c_ubyte`. |
| 2305 |
|
| 2306 |
|
| 2307 |
.. class:: c_uint16 |
| 2308 |
|
| 2309 |
Represents the C 16-bit :c:type:`unsigned int` datatype. Usually an alias for |
| 2310 |
:class:`c_ushort`. |
| 2311 |
|
| 2312 |
|
| 2313 |
.. class:: c_uint32 |
| 2314 |
|
| 2315 |
Represents the C 32-bit :c:type:`unsigned int` datatype. Usually an alias for |
| 2316 |
:class:`c_uint`. |
| 2317 |
|
| 2318 |
|
| 2319 |
.. class:: c_uint64 |
| 2320 |
|
| 2321 |
Represents the C 64-bit :c:type:`unsigned int` datatype. Usually an alias for |
| 2322 |
:class:`c_ulonglong`. |
| 2323 |
|
| 2324 |
|
| 2325 |
.. class:: c_ulong |
| 2326 |
|
| 2327 |
Represents the C :c:type:`unsigned long` datatype. The constructor accepts an |
| 2328 |
optional integer initializer; no overflow checking is done. |
| 2329 |
|
| 2330 |
|
| 2331 |
.. class:: c_ulonglong |
| 2332 |
|
| 2333 |
Represents the C :c:type:`unsigned long long` datatype. The constructor |
| 2334 |
accepts an optional integer initializer; no overflow checking is done. |
| 2335 |
|
| 2336 |
|
| 2337 |
.. class:: c_ushort |
| 2338 |
|
| 2339 |
Represents the C :c:type:`unsigned short` datatype. The constructor accepts |
| 2340 |
an optional integer initializer; no overflow checking is done. |
| 2341 |
|
| 2342 |
|
| 2343 |
.. class:: c_void_p |
| 2344 |
|
| 2345 |
Represents the C :c:type:`void *` type. The value is represented as integer. |
| 2346 |
The constructor accepts an optional integer initializer. |
| 2347 |
|
| 2348 |
|
| 2349 |
.. class:: c_wchar |
| 2350 |
|
| 2351 |
Represents the C :c:type:`wchar_t` datatype, and interprets the value as a |
| 2352 |
single character unicode string. The constructor accepts an optional string |
| 2353 |
initializer, the length of the string must be exactly one character. |
| 2354 |
|
| 2355 |
|
| 2356 |
.. class:: c_wchar_p |
| 2357 |
|
| 2358 |
Represents the C :c:type:`wchar_t *` datatype, which must be a pointer to a |
| 2359 |
zero-terminated wide character string. The constructor accepts an integer |
| 2360 |
address, or a string. |
| 2361 |
|
| 2362 |
|
| 2363 |
.. class:: c_bool |
| 2364 |
|
| 2365 |
Represent the C :c:type:`bool` datatype (more accurately, :c:type:`_Bool` from |
| 2366 |
C99). Its value can be ``True`` or ``False``, and the constructor accepts any object |
| 2367 |
that has a truth value. |
| 2368 |
|
| 2369 |
.. versionadded:: 2.6 |
| 2370 |
|
| 2371 |
|
| 2372 |
.. class:: HRESULT |
| 2373 |
|
| 2374 |
Windows only: Represents a :c:type:`HRESULT` value, which contains success or |
| 2375 |
error information for a function or method call. |
| 2376 |
|
| 2377 |
|
| 2378 |
.. class:: py_object |
| 2379 |
|
| 2380 |
Represents the C :c:type:`PyObject *` datatype. Calling this without an |
| 2381 |
argument creates a ``NULL`` :c:type:`PyObject *` pointer. |
| 2382 |
|
| 2383 |
The :mod:`ctypes.wintypes` module provides quite some other Windows specific |
| 2384 |
data types, for example :c:type:`HWND`, :c:type:`WPARAM`, or :c:type:`DWORD`. Some |
| 2385 |
useful structures like :c:type:`MSG` or :c:type:`RECT` are also defined. |
| 2386 |
|
| 2387 |
|
| 2388 |
.. _ctypes-structured-data-types: |
| 2389 |
|
| 2390 |
Structured data types |
| 2391 |
^^^^^^^^^^^^^^^^^^^^^ |
| 2392 |
|
| 2393 |
|
| 2394 |
.. class:: Union(*args, **kw) |
| 2395 |
|
| 2396 |
Abstract base class for unions in native byte order. |
| 2397 |
|
| 2398 |
|
| 2399 |
.. class:: BigEndianStructure(*args, **kw) |
| 2400 |
|
| 2401 |
Abstract base class for structures in *big endian* byte order. |
| 2402 |
|
| 2403 |
|
| 2404 |
.. class:: LittleEndianStructure(*args, **kw) |
| 2405 |
|
| 2406 |
Abstract base class for structures in *little endian* byte order. |
| 2407 |
|
| 2408 |
Structures with non-native byte order cannot contain pointer type fields, or any |
| 2409 |
other data types containing pointer type fields. |
| 2410 |
|
| 2411 |
|
| 2412 |
.. class:: Structure(*args, **kw) |
| 2413 |
|
| 2414 |
Abstract base class for structures in *native* byte order. |
| 2415 |
|
| 2416 |
Concrete structure and union types must be created by subclassing one of these |
| 2417 |
types, and at least define a :attr:`_fields_` class variable. :mod:`ctypes` will |
| 2418 |
create :term:`descriptor`\s which allow reading and writing the fields by direct |
| 2419 |
attribute accesses. These are the |
| 2420 |
|
| 2421 |
|
| 2422 |
.. attribute:: _fields_ |
| 2423 |
|
| 2424 |
A sequence defining the structure fields. The items must be 2-tuples or |
| 2425 |
3-tuples. The first item is the name of the field, the second item |
| 2426 |
specifies the type of the field; it can be any ctypes data type. |
| 2427 |
|
| 2428 |
For integer type fields like :class:`c_int`, a third optional item can be |
| 2429 |
given. It must be a small positive integer defining the bit width of the |
| 2430 |
field. |
| 2431 |
|
| 2432 |
Field names must be unique within one structure or union. This is not |
| 2433 |
checked, only one field can be accessed when names are repeated. |
| 2434 |
|
| 2435 |
It is possible to define the :attr:`_fields_` class variable *after* the |
| 2436 |
class statement that defines the Structure subclass, this allows creating |
| 2437 |
data types that directly or indirectly reference themselves:: |
| 2438 |
|
| 2439 |
class List(Structure): |
| 2440 |
pass |
| 2441 |
List._fields_ = [("pnext", POINTER(List)), |
| 2442 |
... |
| 2443 |
] |
| 2444 |
|
| 2445 |
The :attr:`_fields_` class variable must, however, be defined before the |
| 2446 |
type is first used (an instance is created, ``sizeof()`` is called on it, |
| 2447 |
and so on). Later assignments to the :attr:`_fields_` class variable will |
| 2448 |
raise an AttributeError. |
| 2449 |
|
| 2450 |
It is possible to defined sub-subclasses of structure types, they inherit |
| 2451 |
the fields of the base class plus the :attr:`_fields_` defined in the |
| 2452 |
sub-subclass, if any. |
| 2453 |
|
| 2454 |
|
| 2455 |
.. attribute:: _pack_ |
| 2456 |
|
| 2457 |
An optional small integer that allows overriding the alignment of |
| 2458 |
structure fields in the instance. :attr:`_pack_` must already be defined |
| 2459 |
when :attr:`_fields_` is assigned, otherwise it will have no effect. |
| 2460 |
|
| 2461 |
|
| 2462 |
.. attribute:: _anonymous_ |
| 2463 |
|
| 2464 |
An optional sequence that lists the names of unnamed (anonymous) fields. |
| 2465 |
:attr:`_anonymous_` must be already defined when :attr:`_fields_` is |
| 2466 |
assigned, otherwise it will have no effect. |
| 2467 |
|
| 2468 |
The fields listed in this variable must be structure or union type fields. |
| 2469 |
:mod:`ctypes` will create descriptors in the structure type that allow |
| 2470 |
accessing the nested fields directly, without the need to create the |
| 2471 |
structure or union field. |
| 2472 |
|
| 2473 |
Here is an example type (Windows):: |
| 2474 |
|
| 2475 |
class _U(Union): |
| 2476 |
_fields_ = [("lptdesc", POINTER(TYPEDESC)), |
| 2477 |
("lpadesc", POINTER(ARRAYDESC)), |
| 2478 |
("hreftype", HREFTYPE)] |
| 2479 |
|
| 2480 |
class TYPEDESC(Structure): |
| 2481 |
_anonymous_ = ("u",) |
| 2482 |
_fields_ = [("u", _U), |
| 2483 |
("vt", VARTYPE)] |
| 2484 |
|
| 2485 |
|
| 2486 |
The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field |
| 2487 |
specifies which one of the union fields is valid. Since the ``u`` field |
| 2488 |
is defined as anonymous field, it is now possible to access the members |
| 2489 |
directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc`` |
| 2490 |
are equivalent, but the former is faster since it does not need to create |
| 2491 |
a temporary union instance:: |
| 2492 |
|
| 2493 |
td = TYPEDESC() |
| 2494 |
td.vt = VT_PTR |
| 2495 |
td.lptdesc = POINTER(some_type) |
| 2496 |
td.u.lptdesc = POINTER(some_type) |
| 2497 |
|
| 2498 |
It is possible to defined sub-subclasses of structures, they inherit the |
| 2499 |
fields of the base class. If the subclass definition has a separate |
| 2500 |
:attr:`_fields_` variable, the fields specified in this are appended to the |
| 2501 |
fields of the base class. |
| 2502 |
|
| 2503 |
Structure and union constructors accept both positional and keyword |
| 2504 |
arguments. Positional arguments are used to initialize member fields in the |
| 2505 |
same order as they are appear in :attr:`_fields_`. Keyword arguments in the |
| 2506 |
constructor are interpreted as attribute assignments, so they will initialize |
| 2507 |
:attr:`_fields_` with the same name, or create new attributes for names not |
| 2508 |
present in :attr:`_fields_`. |
| 2509 |
|
| 2510 |
|
| 2511 |
.. _ctypes-arrays-pointers: |
| 2512 |
|
| 2513 |
Arrays and pointers |
| 2514 |
^^^^^^^^^^^^^^^^^^^ |
| 2515 |
|
| 2516 |
.. class:: Array(\*args) |
| 2517 |
|
| 2518 |
Abstract base class for arrays. |
| 2519 |
|
| 2520 |
The recommended way to create concrete array types is by multiplying any |
| 2521 |
:mod:`ctypes` data type with a positive integer. Alternatively, you can subclass |
| 2522 |
this type and define :attr:`_length_` and :attr:`_type_` class variables. |
| 2523 |
Array elements can be read and written using standard |
| 2524 |
subscript and slice accesses; for slice reads, the resulting object is |
| 2525 |
*not* itself an :class:`Array`. |
| 2526 |
|
| 2527 |
|
| 2528 |
.. attribute:: _length_ |
| 2529 |
|
| 2530 |
A positive integer specifying the number of elements in the array. |
| 2531 |
Out-of-range subscripts result in an :exc:`IndexError`. Will be |
| 2532 |
returned by :func:`len`. |
| 2533 |
|
| 2534 |
|
| 2535 |
.. attribute:: _type_ |
| 2536 |
|
| 2537 |
Specifies the type of each element in the array. |
| 2538 |
|
| 2539 |
|
| 2540 |
Array subclass constructors accept positional arguments, used to |
| 2541 |
initialize the elements in order. |
| 2542 |
|
| 2543 |
|
| 2544 |
.. class:: _Pointer |
| 2545 |
|
| 2546 |
Private, abstract base class for pointers. |
| 2547 |
|
| 2548 |
Concrete pointer types are created by calling :func:`POINTER` with the |
| 2549 |
type that will be pointed to; this is done automatically by |
| 2550 |
:func:`pointer`. |
| 2551 |
|
| 2552 |
If a pointer points to an array, its elements can be read and |
| 2553 |
written using standard subscript and slice accesses. Pointer objects |
| 2554 |
have no size, so :func:`len` will raise :exc:`TypeError`. Negative |
| 2555 |
subscripts will read from the memory *before* the pointer (as in C), and |
| 2556 |
out-of-range subscripts will probably crash with an access violation (if |
| 2557 |
you're lucky). |
| 2558 |
|
| 2559 |
|
| 2560 |
.. attribute:: _type_ |
| 2561 |
|
| 2562 |
Specifies the type pointed to. |
| 2563 |
|
| 2564 |
.. attribute:: contents |
| 2565 |
|
| 2566 |
Returns the object to which to pointer points. Assigning to this |
| 2567 |
attribute changes the pointer to point to the assigned object. |
| 2568 |
|