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