| 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 <[email protected]> |
| 8 |
|
| 9 |
**Source code:** :source:`Lib/ctypes` |
| 10 |
|
| 11 |
-------------- |
| 12 |
|
| 13 |
:mod:`!ctypes` is a foreign function library for Python. It provides C compatible |
| 14 |
data types, and allows calling functions in DLLs or shared libraries. It can be |
| 15 |
used to wrap these libraries in pure Python. |
| 16 |
|
| 17 |
.. include:: ../includes/optional-module.rst |
| 18 |
|
| 19 |
.. warning:: |
| 20 |
|
| 21 |
:mod:`!ctypes` provides low-level access to native libraries and the |
| 22 |
process's memory, bypassing Python's safety mechanisms and allowing |
| 23 |
execution of arbitrary native code. |
| 24 |
Incorrect use can corrupt data and objects, reveal sensitive information, |
| 25 |
cause crashes, or otherwise compromise the running process. |
| 26 |
|
| 27 |
|
| 28 |
.. _ctypes-ctypes-tutorial: |
| 29 |
|
| 30 |
ctypes tutorial |
| 31 |
--------------- |
| 32 |
|
| 33 |
Note: Some code samples reference the ctypes :class:`c_int` type. On platforms |
| 34 |
where ``sizeof(long) == sizeof(int)`` it is an alias to :class:`c_long`. |
| 35 |
So, you should not be confused if :class:`c_long` is printed if you would expect |
| 36 |
:class:`c_int` --- they are actually the same type. |
| 37 |
|
| 38 |
.. _ctypes-loading-dynamic-link-libraries: |
| 39 |
|
| 40 |
Loading dynamic link libraries |
| 41 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 42 |
|
| 43 |
:mod:`!ctypes` exports the :py:data:`~ctypes.cdll`, and on Windows |
| 44 |
:py:data:`~ctypes.windll` and :py:data:`~ctypes.oledll` |
| 45 |
objects, for loading dynamic link libraries. |
| 46 |
|
| 47 |
You load libraries by accessing them as attributes of these objects. |
| 48 |
:py:data:`!cdll` loads libraries which export functions using the |
| 49 |
standard ``cdecl`` calling convention, while :py:data:`!windll` |
| 50 |
libraries call functions using the ``stdcall`` |
| 51 |
calling convention. |
| 52 |
:py:data:`~oledll` also uses the ``stdcall`` calling convention, and |
| 53 |
assumes the functions return a Windows :c:type:`!HRESULT` error code. The error |
| 54 |
code is used to automatically raise an :class:`OSError` exception when the |
| 55 |
function call fails. |
| 56 |
|
| 57 |
.. versionchanged:: 3.3 |
| 58 |
Windows errors used to raise :exc:`WindowsError`, which is now an alias |
| 59 |
of :exc:`OSError`. |
| 60 |
|
| 61 |
|
| 62 |
Here are some examples for Windows. Note that ``msvcrt`` is the MS standard C |
| 63 |
library containing most standard C functions, and uses the ``cdecl`` calling |
| 64 |
convention:: |
| 65 |
|
| 66 |
>>> from ctypes import * |
| 67 |
>>> print(windll.kernel32) # doctest: +WINDOWS |
| 68 |
<WinDLL 'kernel32', handle ... at ...> |
| 69 |
>>> print(cdll.msvcrt) # doctest: +WINDOWS |
| 70 |
<CDLL 'msvcrt', handle ... at ...> |
| 71 |
>>> libc = cdll.msvcrt # doctest: +WINDOWS |
| 72 |
>>> |
| 73 |
|
| 74 |
Windows appends the usual ``.dll`` file suffix automatically. |
| 75 |
|
| 76 |
.. note:: |
| 77 |
Accessing the standard C library through ``cdll.msvcrt`` will use an |
| 78 |
outdated version of the library that may be incompatible with the one |
| 79 |
being used by Python. Where possible, use native Python functionality, |
| 80 |
or else import and use the ``msvcrt`` module. |
| 81 |
|
| 82 |
Other systems require the filename *including* the extension to |
| 83 |
load a library, so attribute access can not be used to load libraries. Either the |
| 84 |
:meth:`~LibraryLoader.LoadLibrary` method of the dll loaders should be used, |
| 85 |
or you should load the library by creating an instance of :py:class:`CDLL` |
| 86 |
by calling the constructor. |
| 87 |
|
| 88 |
For example, on Linux:: |
| 89 |
|
| 90 |
>>> cdll.LoadLibrary("libc.so.6") # doctest: +LINUX |
| 91 |
<CDLL 'libc.so.6', handle ... at ...> |
| 92 |
>>> libc = CDLL("libc.so.6") # doctest: +LINUX |
| 93 |
>>> libc # doctest: +LINUX |
| 94 |
<CDLL 'libc.so.6', handle ... at ...> |
| 95 |
>>> |
| 96 |
|
| 97 |
On macOS:: |
| 98 |
|
| 99 |
>>> cdll.LoadLibrary("libc.dylib") # doctest: +MACOS |
| 100 |
<CDLL 'libc.dylib', handle ... at ...> |
| 101 |
>>> libc = CDLL("libc.dylib") # doctest: +MACOS |
| 102 |
>>> libc # doctest: +MACOS |
| 103 |
<CDLL 'libc.dylib', handle ... at ...> |
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
.. _ctypes-accessing-functions-from-loaded-dlls: |
| 108 |
|
| 109 |
Accessing functions from loaded dlls |
| 110 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 111 |
|
| 112 |
Functions are accessed as attributes of dll objects:: |
| 113 |
|
| 114 |
>>> libc.printf |
| 115 |
<_FuncPtr object at 0x...> |
| 116 |
>>> print(windll.kernel32.GetModuleHandleA) # doctest: +WINDOWS |
| 117 |
<_FuncPtr object at 0x...> |
| 118 |
>>> print(windll.kernel32.MyOwnFunction) # doctest: +WINDOWS |
| 119 |
Traceback (most recent call last): |
| 120 |
File "<stdin>", line 1, in <module> |
| 121 |
File "ctypes.py", line 239, in __getattr__ |
| 122 |
func = _StdcallFuncPtr(name, self) |
| 123 |
AttributeError: function 'MyOwnFunction' not found |
| 124 |
>>> |
| 125 |
|
| 126 |
Note that win32 system dlls like ``kernel32`` and ``user32`` often export ANSI |
| 127 |
as well as UNICODE versions of a function. The UNICODE version is exported with |
| 128 |
a ``W`` appended to the name, while the ANSI version is exported with an ``A`` |
| 129 |
appended to the name. The win32 ``GetModuleHandle`` function, which returns a |
| 130 |
*module handle* for a given module name, has the following C prototype, and a |
| 131 |
macro is used to expose one of them as ``GetModuleHandle`` depending on whether |
| 132 |
UNICODE is defined or not:: |
| 133 |
|
| 134 |
/* ANSI version */ |
| 135 |
HMODULE GetModuleHandleA(LPCSTR lpModuleName); |
| 136 |
/* UNICODE version */ |
| 137 |
HMODULE GetModuleHandleW(LPCWSTR lpModuleName); |
| 138 |
|
| 139 |
*windll* does not try to select one of them by magic, you must access the |
| 140 |
version you need by specifying ``GetModuleHandleA`` or ``GetModuleHandleW`` |
| 141 |
explicitly, and then call it with bytes or string objects respectively. |
| 142 |
|
| 143 |
Sometimes, dlls export functions with names which aren't valid Python |
| 144 |
identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use |
| 145 |
:func:`getattr` to retrieve the function:: |
| 146 |
|
| 147 |
>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") # doctest: +WINDOWS |
| 148 |
<_FuncPtr object at 0x...> |
| 149 |
>>> |
| 150 |
|
| 151 |
On Windows, some dlls export functions not by name but by ordinal. These |
| 152 |
functions can be accessed by indexing the dll object with the ordinal number:: |
| 153 |
|
| 154 |
>>> cdll.kernel32[1] # doctest: +WINDOWS |
| 155 |
<_FuncPtr object at 0x...> |
| 156 |
>>> cdll.kernel32[0] # doctest: +WINDOWS |
| 157 |
Traceback (most recent call last): |
| 158 |
File "<stdin>", line 1, in <module> |
| 159 |
File "ctypes.py", line 310, in __getitem__ |
| 160 |
func = _StdcallFuncPtr(name, self) |
| 161 |
AttributeError: function ordinal 0 not found |
| 162 |
>>> |
| 163 |
|
| 164 |
|
| 165 |
.. _ctypes-calling-functions: |
| 166 |
|
| 167 |
Calling functions |
| 168 |
^^^^^^^^^^^^^^^^^ |
| 169 |
|
| 170 |
You can call these functions like any other Python callable. This example uses |
| 171 |
the ``rand()`` function, which takes no arguments and returns a pseudo-random integer:: |
| 172 |
|
| 173 |
>>> print(libc.rand()) # doctest: +SKIP |
| 174 |
1804289383 |
| 175 |
|
| 176 |
On Windows, you can call the ``GetModuleHandleA()`` function, which returns a win32 module |
| 177 |
handle (passing ``None`` as single argument to call it with a ``NULL`` pointer):: |
| 178 |
|
| 179 |
>>> print(hex(windll.kernel32.GetModuleHandleA(None))) # doctest: +WINDOWS |
| 180 |
0x1d000000 |
| 181 |
>>> |
| 182 |
|
| 183 |
:exc:`ValueError` is raised when you call an ``stdcall`` function with the |
| 184 |
``cdecl`` calling convention, or vice versa:: |
| 185 |
|
| 186 |
>>> cdll.kernel32.GetModuleHandleA(None) # doctest: +WINDOWS |
| 187 |
Traceback (most recent call last): |
| 188 |
File "<stdin>", line 1, in <module> |
| 189 |
ValueError: Procedure probably called with not enough arguments (4 bytes missing) |
| 190 |
>>> |
| 191 |
|
| 192 |
>>> windll.msvcrt.printf(b"spam") # doctest: +WINDOWS |
| 193 |
Traceback (most recent call last): |
| 194 |
File "<stdin>", line 1, in <module> |
| 195 |
ValueError: Procedure probably called with too many arguments (4 bytes in excess) |
| 196 |
>>> |
| 197 |
|
| 198 |
To find out the correct calling convention you have to look into the C header |
| 199 |
file or the documentation for the function you want to call. |
| 200 |
|
| 201 |
On Windows, :mod:`!ctypes` uses win32 structured exception handling to prevent |
| 202 |
crashes from general protection faults when functions are called with invalid |
| 203 |
argument values:: |
| 204 |
|
| 205 |
>>> windll.kernel32.GetModuleHandleA(32) # doctest: +WINDOWS |
| 206 |
Traceback (most recent call last): |
| 207 |
File "<stdin>", line 1, in <module> |
| 208 |
OSError: exception: access violation reading 0x00000020 |
| 209 |
>>> |
| 210 |
|
| 211 |
The :mod:`faulthandler` module can help debug crashes, |
| 212 |
such as segmentation faults produced by erroneous C library calls. |
| 213 |
|
| 214 |
``None``, integers, bytes objects and (unicode) strings are the only native |
| 215 |
Python objects that can directly be used as parameters in these function calls. |
| 216 |
``None`` is passed as a C ``NULL`` pointer, bytes objects and strings are passed |
| 217 |
as pointer to the memory block that contains their data (:c:expr:`char *` or |
| 218 |
:c:expr:`wchar_t *`). Python integers are passed as the platform's default C |
| 219 |
:c:expr:`int` type, their value is masked to fit into the C type. |
| 220 |
|
| 221 |
Before we move on calling functions with other parameter types, we have to learn |
| 222 |
more about :mod:`!ctypes` data types. |
| 223 |
|
| 224 |
|
| 225 |
.. _ctypes-fundamental-data-types: |
| 226 |
|
| 227 |
Fundamental data types |
| 228 |
^^^^^^^^^^^^^^^^^^^^^^ |
| 229 |
|
| 230 |
:mod:`!ctypes` defines a number of primitive C compatible data types: |
| 231 |
|
| 232 |
.. list-table:: |
| 233 |
:header-rows: 1 |
| 234 |
|
| 235 |
* - ctypes type |
| 236 |
- C type |
| 237 |
- Python type |
| 238 |
- :py:attr:`~_SimpleCData._type_` |
| 239 |
* - :class:`c_bool` |
| 240 |
- :c:expr:`_Bool` |
| 241 |
- :py:class:`bool` |
| 242 |
- ``'?'`` |
| 243 |
* - :class:`c_char` |
| 244 |
- :c:expr:`char` |
| 245 |
- 1-character :py:class:`bytes` |
| 246 |
- ``'c'`` |
| 247 |
* - :class:`c_wchar` |
| 248 |
- :c:type:`wchar_t` |
| 249 |
- 1-character :py:class:`str` |
| 250 |
- ``'u'`` |
| 251 |
* - :class:`c_byte` |
| 252 |
- :c:expr:`char` |
| 253 |
- :py:class:`int` |
| 254 |
- ``'b'`` |
| 255 |
* - :class:`c_ubyte` |
| 256 |
- :c:expr:`unsigned char` |
| 257 |
- :py:class:`int` |
| 258 |
- ``'B'`` |
| 259 |
* - :class:`c_short` |
| 260 |
- :c:expr:`short` |
| 261 |
- :py:class:`int` |
| 262 |
- ``'h'`` |
| 263 |
* - :class:`c_ushort` |
| 264 |
- :c:expr:`unsigned short` |
| 265 |
- :py:class:`int` |
| 266 |
- ``'H'`` |
| 267 |
* - :class:`c_int` |
| 268 |
- :c:expr:`int` |
| 269 |
- :py:class:`int` |
| 270 |
- ``'i'`` \* |
| 271 |
* - :class:`c_int8` |
| 272 |
- :c:type:`int8_t` |
| 273 |
- :py:class:`int` |
| 274 |
- \* |
| 275 |
* - :class:`c_int16` |
| 276 |
- :c:type:`int16_t` |
| 277 |
- :py:class:`int` |
| 278 |
- \* |
| 279 |
* - :class:`c_int32` |
| 280 |
- :c:type:`int32_t` |
| 281 |
- :py:class:`int` |
| 282 |
- \* |
| 283 |
* - :class:`c_int64` |
| 284 |
- :c:type:`int64_t` |
| 285 |
- :py:class:`int` |
| 286 |
- \* |
| 287 |
* - :class:`c_uint` |
| 288 |
- :c:expr:`unsigned int` |
| 289 |
- :py:class:`int` |
| 290 |
- ``'I'`` \* |
| 291 |
* - :class:`c_uint8` |
| 292 |
- :c:type:`uint8_t` |
| 293 |
- :py:class:`int` |
| 294 |
- \* |
| 295 |
* - :class:`c_uint16` |
| 296 |
- :c:type:`uint16_t` |
| 297 |
- :py:class:`int` |
| 298 |
- \* |
| 299 |
* - :class:`c_uint32` |
| 300 |
- :c:type:`uint32_t` |
| 301 |
- :py:class:`int` |
| 302 |
- \* |
| 303 |
* - :class:`c_uint64` |
| 304 |
- :c:type:`uint64_t` |
| 305 |
- :py:class:`int` |
| 306 |
- \* |
| 307 |
* - :class:`c_long` |
| 308 |
- :c:expr:`long` |
| 309 |
- :py:class:`int` |
| 310 |
- ``'l'`` |
| 311 |
* - :class:`c_ulong` |
| 312 |
- :c:expr:`unsigned long` |
| 313 |
- :py:class:`int` |
| 314 |
- ``'L'`` |
| 315 |
* - :class:`c_longlong` |
| 316 |
- :c:expr:`long long` |
| 317 |
- :py:class:`int` |
| 318 |
- ``'q'`` \* |
| 319 |
* - :class:`c_ulonglong` |
| 320 |
- :c:expr:`unsigned long long` |
| 321 |
- :py:class:`int` |
| 322 |
- ``'Q'`` \* |
| 323 |
* - :class:`c_size_t` |
| 324 |
- :c:type:`size_t` |
| 325 |
- :py:class:`int` |
| 326 |
- \* |
| 327 |
* - :class:`c_ssize_t` |
| 328 |
- :c:type:`Py_ssize_t` |
| 329 |
- :py:class:`int` |
| 330 |
- \* |
| 331 |
* - :class:`c_time_t` |
| 332 |
- :c:type:`time_t` |
| 333 |
- :py:class:`int` |
| 334 |
- \* |
| 335 |
* - :class:`c_float` |
| 336 |
- :c:expr:`float` |
| 337 |
- :py:class:`float` |
| 338 |
- ``'f'`` |
| 339 |
* - :class:`c_double` |
| 340 |
- :c:expr:`double` |
| 341 |
- :py:class:`float` |
| 342 |
- ``'d'`` |
| 343 |
* - :class:`c_longdouble` |
| 344 |
- :c:expr:`long double` |
| 345 |
- :py:class:`float` |
| 346 |
- ``'g'`` \* |
| 347 |
* - :class:`c_char_p` |
| 348 |
- :c:expr:`char *` (NUL terminated) |
| 349 |
- :py:class:`bytes` or ``None`` |
| 350 |
- ``'z'`` |
| 351 |
* - :class:`c_wchar_p` |
| 352 |
- :c:expr:`wchar_t *` (NUL terminated) |
| 353 |
- :py:class:`str` or ``None`` |
| 354 |
- ``'Z'`` |
| 355 |
* - :class:`c_void_p` |
| 356 |
- :c:expr:`void *` |
| 357 |
- :py:class:`int` or ``None`` |
| 358 |
- ``'P'`` |
| 359 |
* - :class:`py_object` |
| 360 |
- :c:expr:`PyObject *` |
| 361 |
- :py:class:`object` |
| 362 |
- ``'O'`` |
| 363 |
* - :ref:`VARIANT_BOOL <ctypes-wintypes>` |
| 364 |
- :c:expr:`short int` |
| 365 |
- :py:class:`bool` |
| 366 |
- ``'v'`` |
| 367 |
|
| 368 |
Additionally, if IEC 60559 compatible complex arithmetic (Annex G) is supported |
| 369 |
in both C and ``libffi``, the following complex types are available: |
| 370 |
|
| 371 |
.. list-table:: |
| 372 |
:header-rows: 1 |
| 373 |
|
| 374 |
* - ctypes type |
| 375 |
- C type |
| 376 |
- Python type |
| 377 |
- :py:attr:`~_SimpleCData._type_` |
| 378 |
* - :class:`c_float_complex` |
| 379 |
- :c:expr:`float complex` |
| 380 |
- :py:class:`complex` |
| 381 |
- ``'F'`` |
| 382 |
* - :class:`c_double_complex` |
| 383 |
- :c:expr:`double complex` |
| 384 |
- :py:class:`complex` |
| 385 |
- ``'D'`` |
| 386 |
* - :class:`c_longdouble_complex` |
| 387 |
- :c:expr:`long double complex` |
| 388 |
- :py:class:`complex` |
| 389 |
- ``'G'`` |
| 390 |
|
| 391 |
|
| 392 |
All these types can be created by calling them with an optional initializer of |
| 393 |
the correct type and value:: |
| 394 |
|
| 395 |
>>> c_int() |
| 396 |
c_long(0) |
| 397 |
>>> c_wchar_p("Hello, World") |
| 398 |
c_wchar_p(140018365411392) |
| 399 |
>>> c_ushort(-3) |
| 400 |
c_ushort(65533) |
| 401 |
>>> |
| 402 |
|
| 403 |
The constructors for numeric types will convert input using |
| 404 |
:py:meth:`~object.__bool__`, |
| 405 |
:py:meth:`~object.__index__` (for ``int``), |
| 406 |
:py:meth:`~object.__float__` or :py:meth:`~object.__complex__`. |
| 407 |
This means :py:class:`~ctypes.c_bool` accepts any object with a truth value:: |
| 408 |
|
| 409 |
>>> empty_list = [] |
| 410 |
>>> c_bool(empty_list) |
| 411 |
c_bool(False) |
| 412 |
|
| 413 |
Since these types are mutable, their value can also be changed afterwards:: |
| 414 |
|
| 415 |
>>> i = c_int(42) |
| 416 |
>>> print(i) |
| 417 |
c_long(42) |
| 418 |
>>> print(i.value) |
| 419 |
42 |
| 420 |
>>> i.value = -99 |
| 421 |
>>> print(i.value) |
| 422 |
-99 |
| 423 |
>>> |
| 424 |
|
| 425 |
Assigning a new value to instances of the pointer types :class:`c_char_p`, |
| 426 |
:class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they |
| 427 |
point to, *not the contents* of the memory block (of course not, because Python |
| 428 |
string objects are immutable):: |
| 429 |
|
| 430 |
>>> s = "Hello, World" |
| 431 |
>>> c_s = c_wchar_p(s) |
| 432 |
>>> print(c_s) |
| 433 |
c_wchar_p(139966785747344) |
| 434 |
>>> print(c_s.value) |
| 435 |
Hello World |
| 436 |
>>> c_s.value = "Hi, there" |
| 437 |
>>> print(c_s) # the memory location has changed |
| 438 |
c_wchar_p(139966783348904) |
| 439 |
>>> print(c_s.value) |
| 440 |
Hi, there |
| 441 |
>>> print(s) # first object is unchanged |
| 442 |
Hello, World |
| 443 |
>>> |
| 444 |
|
| 445 |
You should be careful, however, not to pass them to functions expecting pointers |
| 446 |
to mutable memory. If you need mutable memory blocks, ctypes has a |
| 447 |
:func:`create_string_buffer` function which creates these in various ways. The |
| 448 |
current memory block contents can be accessed (or changed) with the ``raw`` |
| 449 |
property; if you want to access it as NUL terminated string, use the ``value`` |
| 450 |
property:: |
| 451 |
|
| 452 |
>>> from ctypes import * |
| 453 |
>>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes |
| 454 |
>>> print(sizeof(p), repr(p.raw)) |
| 455 |
3 b'\x00\x00\x00' |
| 456 |
>>> p = create_string_buffer(b"Hello") # create a buffer containing a NUL terminated string |
| 457 |
>>> print(sizeof(p), repr(p.raw)) |
| 458 |
6 b'Hello\x00' |
| 459 |
>>> print(repr(p.value)) |
| 460 |
b'Hello' |
| 461 |
>>> p = create_string_buffer(b"Hello", 10) # create a 10 byte buffer |
| 462 |
>>> print(sizeof(p), repr(p.raw)) |
| 463 |
10 b'Hello\x00\x00\x00\x00\x00' |
| 464 |
>>> p.value = b"Hi" |
| 465 |
>>> print(sizeof(p), repr(p.raw)) |
| 466 |
10 b'Hi\x00lo\x00\x00\x00\x00\x00' |
| 467 |
>>> |
| 468 |
|
| 469 |
The :func:`create_string_buffer` function replaces the old :func:`!c_buffer` |
| 470 |
function (which is still available as an alias). To create a mutable memory |
| 471 |
block containing unicode characters of the C type :c:type:`wchar_t`, use the |
| 472 |
:func:`create_unicode_buffer` function. |
| 473 |
|
| 474 |
|
| 475 |
.. _ctypes-calling-functions-continued: |
| 476 |
|
| 477 |
Calling functions, continued |
| 478 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 479 |
|
| 480 |
Note that printf prints to the real standard output channel, *not* to |
| 481 |
:data:`sys.stdout`, so these examples will only work at the console prompt, not |
| 482 |
from within *IDLE* or *PythonWin*:: |
| 483 |
|
| 484 |
>>> printf = libc.printf |
| 485 |
>>> printf(b"Hello, %s\n", b"World!") |
| 486 |
Hello, World! |
| 487 |
14 |
| 488 |
>>> printf(b"Hello, %S\n", "World!") |
| 489 |
Hello, World! |
| 490 |
14 |
| 491 |
>>> printf(b"%d bottles of beer\n", 42) |
| 492 |
42 bottles of beer |
| 493 |
19 |
| 494 |
>>> printf(b"%f bottles of beer\n", 42.5) |
| 495 |
Traceback (most recent call last): |
| 496 |
File "<stdin>", line 1, in <module> |
| 497 |
ctypes.ArgumentError: argument 2: TypeError: Don't know how to convert parameter 2 |
| 498 |
>>> |
| 499 |
|
| 500 |
As has been mentioned before, all Python types except integers, strings, and |
| 501 |
bytes objects have to be wrapped in their corresponding :mod:`!ctypes` type, so |
| 502 |
that they can be converted to the required C data type:: |
| 503 |
|
| 504 |
>>> printf(b"An int %d, a double %f\n", 1234, c_double(3.14)) |
| 505 |
An int 1234, a double 3.140000 |
| 506 |
31 |
| 507 |
>>> |
| 508 |
|
| 509 |
.. _ctypes-calling-variadic-functions: |
| 510 |
|
| 511 |
Calling variadic functions |
| 512 |
^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 513 |
|
| 514 |
On a lot of platforms calling variadic functions through ctypes is exactly the same |
| 515 |
as calling functions with a fixed number of parameters. On some platforms, and in |
| 516 |
particular ARM64 for Apple Platforms, the calling convention for variadic functions |
| 517 |
is different than that for regular functions. |
| 518 |
|
| 519 |
On those platforms it is required to specify the :attr:`~_CFuncPtr.argtypes` |
| 520 |
attribute for the regular, non-variadic, function arguments: |
| 521 |
|
| 522 |
.. code-block:: python3 |
| 523 |
|
| 524 |
libc.printf.argtypes = [ctypes.c_char_p] |
| 525 |
|
| 526 |
Because specifying the attribute does not inhibit portability it is advised to always |
| 527 |
specify :attr:`~_CFuncPtr.argtypes` for all variadic functions. |
| 528 |
|
| 529 |
|
| 530 |
.. _ctypes-calling-functions-with-own-custom-data-types: |
| 531 |
|
| 532 |
Calling functions with your own custom data types |
| 533 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 534 |
|
| 535 |
You can also customize :mod:`!ctypes` argument conversion to allow instances of |
| 536 |
your own classes be used as function arguments. :mod:`!ctypes` looks for an |
| 537 |
:attr:`!_as_parameter_` attribute and uses this as the function argument. The |
| 538 |
attribute must be an integer, string, bytes, a :mod:`!ctypes` instance, or an |
| 539 |
object with an :attr:`!_as_parameter_` attribute:: |
| 540 |
|
| 541 |
>>> class Bottles: |
| 542 |
... def __init__(self, number): |
| 543 |
... self._as_parameter_ = number |
| 544 |
... |
| 545 |
>>> bottles = Bottles(42) |
| 546 |
>>> printf(b"%d bottles of beer\n", bottles) |
| 547 |
42 bottles of beer |
| 548 |
19 |
| 549 |
>>> |
| 550 |
|
| 551 |
If you don't want to store the instance's data in the :attr:`!_as_parameter_` |
| 552 |
instance variable, you could define a :class:`property` which makes the |
| 553 |
attribute available on request. |
| 554 |
|
| 555 |
|
| 556 |
.. _ctypes-specifying-required-argument-types: |
| 557 |
|
| 558 |
Specifying the required argument types (function prototypes) |
| 559 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 560 |
|
| 561 |
It is possible to specify the required argument types of functions exported from |
| 562 |
DLLs by setting the :attr:`~_CFuncPtr.argtypes` attribute. |
| 563 |
|
| 564 |
:attr:`~_CFuncPtr.argtypes` must be a sequence of C data types (the :func:`!printf` function is |
| 565 |
probably not a good example here, because it takes a variable number and |
| 566 |
different types of parameters depending on the format string, on the other hand |
| 567 |
this is quite handy to experiment with this feature):: |
| 568 |
|
| 569 |
>>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double] |
| 570 |
>>> printf(b"String '%s', Int %d, Double %f\n", b"Hi", 10, 2.2) |
| 571 |
String 'Hi', Int 10, Double 2.200000 |
| 572 |
37 |
| 573 |
>>> |
| 574 |
|
| 575 |
Specifying a format protects against incompatible argument types (just as a |
| 576 |
prototype for a C function), and tries to convert the arguments to valid types:: |
| 577 |
|
| 578 |
>>> printf(b"%d %d %d", 1, 2, 3) |
| 579 |
Traceback (most recent call last): |
| 580 |
File "<stdin>", line 1, in <module> |
| 581 |
ctypes.ArgumentError: argument 2: TypeError: 'int' object cannot be interpreted as ctypes.c_char_p |
| 582 |
>>> printf(b"%s %d %f\n", b"X", 2, 3) |
| 583 |
X 2 3.000000 |
| 584 |
13 |
| 585 |
>>> |
| 586 |
|
| 587 |
If you have defined your own classes which you pass to function calls, you have |
| 588 |
to implement a :meth:`~_CData.from_param` class method for them to be able to use them |
| 589 |
in the :attr:`~_CFuncPtr.argtypes` sequence. The :meth:`~_CData.from_param` class method receives |
| 590 |
the Python object passed to the function call, it should do a typecheck or |
| 591 |
whatever is needed to make sure this object is acceptable, and then return the |
| 592 |
object itself, its :attr:`!_as_parameter_` attribute, or whatever you want to |
| 593 |
pass as the C function argument in this case. Again, the result should be an |
| 594 |
integer, string, bytes, a :mod:`!ctypes` instance, or an object with an |
| 595 |
:attr:`!_as_parameter_` attribute. |
| 596 |
|
| 597 |
|
| 598 |
.. _ctypes-return-types: |
| 599 |
|
| 600 |
Return types |
| 601 |
^^^^^^^^^^^^ |
| 602 |
|
| 603 |
.. testsetup:: |
| 604 |
|
| 605 |
from ctypes import CDLL, c_char, c_char_p |
| 606 |
from ctypes.util import find_library |
| 607 |
libc = CDLL(find_library('c')) |
| 608 |
strchr = libc.strchr |
| 609 |
|
| 610 |
|
| 611 |
By default functions are assumed to return the C :c:expr:`int` type. Other |
| 612 |
return types can be specified by setting the :attr:`~_CFuncPtr.restype` attribute of the |
| 613 |
function object. |
| 614 |
|
| 615 |
The C prototype of :c:func:`time` is ``time_t time(time_t *)``. Because :c:type:`time_t` |
| 616 |
might be of a different type than the default return type :c:expr:`int`, you should |
| 617 |
specify the :attr:`!restype` attribute:: |
| 618 |
|
| 619 |
>>> libc.time.restype = c_time_t |
| 620 |
|
| 621 |
The argument types can be specified using :attr:`~_CFuncPtr.argtypes`:: |
| 622 |
|
| 623 |
>>> libc.time.argtypes = (POINTER(c_time_t),) |
| 624 |
|
| 625 |
To call the function with a ``NULL`` pointer as first argument, use ``None``:: |
| 626 |
|
| 627 |
>>> print(libc.time(None)) # doctest: +SKIP |
| 628 |
1150640792 |
| 629 |
|
| 630 |
Here is a more advanced example, it uses the :func:`!strchr` function, which expects |
| 631 |
a string pointer and a char, and returns a pointer to a string:: |
| 632 |
|
| 633 |
>>> strchr = libc.strchr |
| 634 |
>>> strchr(b"abcdef", ord("d")) # doctest: +SKIP |
| 635 |
8059983 |
| 636 |
>>> strchr.restype = c_char_p # c_char_p is a pointer to a string |
| 637 |
>>> strchr(b"abcdef", ord("d")) |
| 638 |
b'def' |
| 639 |
>>> print(strchr(b"abcdef", ord("x"))) |
| 640 |
None |
| 641 |
>>> |
| 642 |
|
| 643 |
If you want to avoid the :func:`ord("x") <ord>` calls above, you can set the |
| 644 |
:attr:`~_CFuncPtr.argtypes` attribute, and the second argument will be converted from a |
| 645 |
single character Python bytes object into a C char: |
| 646 |
|
| 647 |
.. doctest:: |
| 648 |
|
| 649 |
>>> strchr.restype = c_char_p |
| 650 |
>>> strchr.argtypes = [c_char_p, c_char] |
| 651 |
>>> strchr(b"abcdef", b"d") |
| 652 |
b'def' |
| 653 |
>>> strchr(b"abcdef", b"def") |
| 654 |
Traceback (most recent call last): |
| 655 |
ctypes.ArgumentError: argument 2: TypeError: one character bytes, bytearray or integer expected |
| 656 |
>>> print(strchr(b"abcdef", b"x")) |
| 657 |
None |
| 658 |
>>> strchr(b"abcdef", b"d") |
| 659 |
b'def' |
| 660 |
>>> |
| 661 |
|
| 662 |
You can also use a callable Python object (a function or a class for example) as |
| 663 |
the :attr:`~_CFuncPtr.restype` attribute, if the foreign function returns an integer. The |
| 664 |
callable will be called with the *integer* the C function returns, and the |
| 665 |
result of this call will be used as the result of your function call. This is |
| 666 |
useful to check for error return values and automatically raise an exception:: |
| 667 |
|
| 668 |
>>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS |
| 669 |
>>> def ValidHandle(value): |
| 670 |
... if value == 0: |
| 671 |
... raise WinError() |
| 672 |
... return value |
| 673 |
... |
| 674 |
>>> |
| 675 |
>>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS |
| 676 |
>>> GetModuleHandle(None) # doctest: +WINDOWS |
| 677 |
486539264 |
| 678 |
>>> GetModuleHandle("something silly") # doctest: +WINDOWS |
| 679 |
Traceback (most recent call last): |
| 680 |
File "<stdin>", line 1, in <module> |
| 681 |
File "<stdin>", line 3, in ValidHandle |
| 682 |
OSError: [Errno 126] The specified module could not be found. |
| 683 |
>>> |
| 684 |
|
| 685 |
``WinError`` is a function which will call Windows ``FormatMessage()`` api to |
| 686 |
get the string representation of an error code, and *returns* an exception. |
| 687 |
``WinError`` takes an optional error code parameter, if no one is used, it calls |
| 688 |
:func:`GetLastError` to retrieve it. |
| 689 |
|
| 690 |
Please note that a much more powerful error checking mechanism is available |
| 691 |
through the :attr:`~_CFuncPtr.errcheck` attribute; |
| 692 |
see the reference manual for details. |
| 693 |
|
| 694 |
|
| 695 |
.. _ctypes-passing-pointers: |
| 696 |
|
| 697 |
Passing pointers (or: passing parameters by reference) |
| 698 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 699 |
|
| 700 |
Sometimes a C api function expects a *pointer* to a data type as parameter, |
| 701 |
probably to write into the corresponding location, or if the data is too large |
| 702 |
to be passed by value. This is also known as *passing parameters by reference*. |
| 703 |
|
| 704 |
:mod:`!ctypes` exports the :func:`byref` function which is used to pass parameters |
| 705 |
by reference. The same effect can be achieved with the :func:`pointer` function, |
| 706 |
although :func:`pointer` does a lot more work since it constructs a real pointer |
| 707 |
object, so it is faster to use :func:`byref` if you don't need the pointer |
| 708 |
object in Python itself:: |
| 709 |
|
| 710 |
>>> i = c_int() |
| 711 |
>>> f = c_float() |
| 712 |
>>> s = create_string_buffer(b'\000' * 32) |
| 713 |
>>> print(i.value, f.value, repr(s.value)) |
| 714 |
0 0.0 b'' |
| 715 |
>>> libc.sscanf(b"1 3.14 Hello", b"%d %f %s", |
| 716 |
... byref(i), byref(f), s) |
| 717 |
3 |
| 718 |
>>> print(i.value, f.value, repr(s.value)) |
| 719 |
1 3.1400001049 b'Hello' |
| 720 |
>>> |
| 721 |
|
| 722 |
|
| 723 |
.. _ctypes-structures-unions: |
| 724 |
|
| 725 |
Structures and unions |
| 726 |
^^^^^^^^^^^^^^^^^^^^^ |
| 727 |
|
| 728 |
Structures and unions must derive from the :class:`Structure` and :class:`Union` |
| 729 |
base classes which are defined in the :mod:`!ctypes` module. Each subclass must |
| 730 |
define a :attr:`~Structure._fields_` attribute. :attr:`!_fields_` must be a list of |
| 731 |
*2-tuples*, containing a *field name* and a *field type*. |
| 732 |
|
| 733 |
The field type must be a :mod:`!ctypes` type like :class:`c_int`, or any other |
| 734 |
derived :mod:`!ctypes` type: structure, union, array, pointer. |
| 735 |
|
| 736 |
Here is a simple example of a POINT structure, which contains two integers named |
| 737 |
*x* and *y*, and also shows how to initialize a structure in the constructor:: |
| 738 |
|
| 739 |
>>> from ctypes import * |
| 740 |
>>> class POINT(Structure): |
| 741 |
... _fields_ = [("x", c_int), |
| 742 |
... ("y", c_int)] |
| 743 |
... |
| 744 |
>>> point = POINT(10, 20) |
| 745 |
>>> print(point.x, point.y) |
| 746 |
10 20 |
| 747 |
>>> point = POINT(y=5) |
| 748 |
>>> print(point.x, point.y) |
| 749 |
0 5 |
| 750 |
>>> POINT(1, 2, 3) |
| 751 |
Traceback (most recent call last): |
| 752 |
File "<stdin>", line 1, in <module> |
| 753 |
TypeError: too many initializers |
| 754 |
>>> |
| 755 |
|
| 756 |
You can, however, build much more complicated structures. A structure can |
| 757 |
itself contain other structures by using a structure as a field type. |
| 758 |
|
| 759 |
Here is a RECT structure which contains two POINTs named *upperleft* and |
| 760 |
*lowerright*:: |
| 761 |
|
| 762 |
>>> class RECT(Structure): |
| 763 |
... _fields_ = [("upperleft", POINT), |
| 764 |
... ("lowerright", POINT)] |
| 765 |
... |
| 766 |
>>> rc = RECT(point) |
| 767 |
>>> print(rc.upperleft.x, rc.upperleft.y) |
| 768 |
0 5 |
| 769 |
>>> print(rc.lowerright.x, rc.lowerright.y) |
| 770 |
0 0 |
| 771 |
>>> |
| 772 |
|
| 773 |
Nested structures can also be initialized in the constructor in several ways:: |
| 774 |
|
| 775 |
>>> r = RECT(POINT(1, 2), POINT(3, 4)) |
| 776 |
>>> r = RECT((1, 2), (3, 4)) |
| 777 |
|
| 778 |
Field :term:`descriptor`\s can be retrieved from the *class*, they are useful |
| 779 |
for debugging because they can provide useful information. |
| 780 |
See :class:`CField`:: |
| 781 |
|
| 782 |
>>> POINT.x |
| 783 |
<ctypes.CField 'x' type=c_int, ofs=0, size=4> |
| 784 |
>>> POINT.y |
| 785 |
<ctypes.CField 'y' type=c_int, ofs=4, size=4> |
| 786 |
>>> |
| 787 |
|
| 788 |
|
| 789 |
.. _ctypes-structureunion-alignment-byte-order: |
| 790 |
|
| 791 |
.. warning:: |
| 792 |
|
| 793 |
:mod:`!ctypes` does not support passing unions or structures with bit-fields |
| 794 |
to functions by value. While this may work on 32-bit x86, it's not |
| 795 |
guaranteed by the library to work in the general case. Unions and |
| 796 |
structures with bit-fields should always be passed to functions by pointer. |
| 797 |
|
| 798 |
Structure/union layout, alignment and byte order |
| 799 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 800 |
|
| 801 |
By default, Structure and Union fields are laid out in the same way the C |
| 802 |
compiler does it. It is possible to override this behavior entirely by specifying a |
| 803 |
:attr:`~Structure._layout_` class attribute in the subclass definition; see |
| 804 |
the attribute documentation for details. |
| 805 |
|
| 806 |
It is possible to specify the maximum alignment for the fields and/or for the |
| 807 |
structure itself by setting the class attributes :attr:`~Structure._pack_` |
| 808 |
and/or :attr:`~Structure._align_`, respectively. |
| 809 |
See the attribute documentation for details. |
| 810 |
|
| 811 |
:mod:`!ctypes` uses the native byte order for Structures and Unions. To build |
| 812 |
structures with non-native byte order, you can use one of the |
| 813 |
:class:`BigEndianStructure`, :class:`LittleEndianStructure`, |
| 814 |
:class:`BigEndianUnion`, and :class:`LittleEndianUnion` base classes. These |
| 815 |
classes cannot contain pointer fields. |
| 816 |
|
| 817 |
|
| 818 |
.. _ctypes-bit-fields-in-structures-unions: |
| 819 |
|
| 820 |
Bit fields in structures and unions |
| 821 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 822 |
|
| 823 |
It is possible to create structures and unions containing bit fields. Bit fields |
| 824 |
are only possible for integer fields, the bit width is specified as the third |
| 825 |
item in the :attr:`~Structure._fields_` tuples:: |
| 826 |
|
| 827 |
>>> class Int(Structure): |
| 828 |
... _fields_ = [("first_16", c_int, 16), |
| 829 |
... ("second_16", c_int, 16)] |
| 830 |
... |
| 831 |
>>> print(Int.first_16) |
| 832 |
<ctypes.CField 'first_16' type=c_int, ofs=0, bit_size=16, bit_offset=0> |
| 833 |
>>> print(Int.second_16) |
| 834 |
<ctypes.CField 'second_16' type=c_int, ofs=0, bit_size=16, bit_offset=16> |
| 835 |
|
| 836 |
It is important to note that bit field allocation and layout in memory are not |
| 837 |
defined as a C standard; their implementation is compiler-specific. |
| 838 |
By default, Python will attempt to match the behavior of a "native" compiler |
| 839 |
for the current platform. |
| 840 |
See the :attr:`~Structure._layout_` attribute for details on the default |
| 841 |
behavior and how to change it. |
| 842 |
|
| 843 |
|
| 844 |
.. _ctypes-arrays: |
| 845 |
|
| 846 |
Arrays |
| 847 |
^^^^^^ |
| 848 |
|
| 849 |
Arrays are sequences, containing a fixed number of instances of the same type. |
| 850 |
|
| 851 |
The recommended way to create array types is by multiplying a data type with a |
| 852 |
positive integer:: |
| 853 |
|
| 854 |
TenPointsArrayType = POINT * 10 |
| 855 |
|
| 856 |
Here is an example of a somewhat artificial data type, a structure containing 4 |
| 857 |
POINTs among other stuff:: |
| 858 |
|
| 859 |
>>> from ctypes import * |
| 860 |
>>> class POINT(Structure): |
| 861 |
... _fields_ = ("x", c_int), ("y", c_int) |
| 862 |
... |
| 863 |
>>> class MyStruct(Structure): |
| 864 |
... _fields_ = [("a", c_int), |
| 865 |
... ("b", c_float), |
| 866 |
... ("point_array", POINT * 4)] |
| 867 |
>>> |
| 868 |
>>> print(len(MyStruct().point_array)) |
| 869 |
4 |
| 870 |
>>> |
| 871 |
|
| 872 |
Instances are created in the usual way, by calling the class:: |
| 873 |
|
| 874 |
arr = TenPointsArrayType() |
| 875 |
for pt in arr: |
| 876 |
print(pt.x, pt.y) |
| 877 |
|
| 878 |
The above code print a series of ``0 0`` lines, because the array contents is |
| 879 |
initialized to zeros. |
| 880 |
|
| 881 |
Initializers of the correct type can also be specified:: |
| 882 |
|
| 883 |
>>> from ctypes import * |
| 884 |
>>> TenIntegers = c_int * 10 |
| 885 |
>>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) |
| 886 |
>>> print(ii) |
| 887 |
<c_long_Array_10 object at 0x...> |
| 888 |
>>> for i in ii: print(i, end=" ") |
| 889 |
... |
| 890 |
1 2 3 4 5 6 7 8 9 10 |
| 891 |
>>> |
| 892 |
|
| 893 |
|
| 894 |
.. _ctypes-pointers: |
| 895 |
|
| 896 |
Pointers |
| 897 |
^^^^^^^^ |
| 898 |
|
| 899 |
Pointer instances are created by calling the :func:`pointer` function on a |
| 900 |
:mod:`!ctypes` type:: |
| 901 |
|
| 902 |
>>> from ctypes import * |
| 903 |
>>> i = c_int(42) |
| 904 |
>>> pi = pointer(i) |
| 905 |
>>> |
| 906 |
|
| 907 |
Pointer instances have a :attr:`~_Pointer.contents` attribute which |
| 908 |
returns the object to which the pointer points, the ``i`` object above:: |
| 909 |
|
| 910 |
>>> pi.contents |
| 911 |
c_long(42) |
| 912 |
>>> |
| 913 |
|
| 914 |
Note that :mod:`!ctypes` does not have OOR (original object return), it constructs a |
| 915 |
new, equivalent object each time you retrieve an attribute:: |
| 916 |
|
| 917 |
>>> pi.contents is i |
| 918 |
False |
| 919 |
>>> pi.contents is pi.contents |
| 920 |
False |
| 921 |
>>> |
| 922 |
|
| 923 |
Assigning another :class:`c_int` instance to the pointer's contents attribute |
| 924 |
would cause the pointer to point to the memory location where this is stored:: |
| 925 |
|
| 926 |
>>> i = c_int(99) |
| 927 |
>>> pi.contents = i |
| 928 |
>>> pi.contents |
| 929 |
c_long(99) |
| 930 |
>>> |
| 931 |
|
| 932 |
.. XXX Document dereferencing pointers, and that it is preferred over the |
| 933 |
.contents attribute. |
| 934 |
|
| 935 |
Pointer instances can also be indexed with integers:: |
| 936 |
|
| 937 |
>>> pi[0] |
| 938 |
99 |
| 939 |
>>> |
| 940 |
|
| 941 |
Assigning to an integer index changes the pointed to value:: |
| 942 |
|
| 943 |
>>> print(i) |
| 944 |
c_long(99) |
| 945 |
>>> pi[0] = 22 |
| 946 |
>>> print(i) |
| 947 |
c_long(22) |
| 948 |
>>> |
| 949 |
|
| 950 |
It is also possible to use indexes different from 0, but you must know what |
| 951 |
you're doing, just as in C: You can access or change arbitrary memory locations. |
| 952 |
Generally you only use this feature if you receive a pointer from a C function, |
| 953 |
and you *know* that the pointer actually points to an array instead of a single |
| 954 |
item. |
| 955 |
|
| 956 |
Behind the scenes, the :func:`pointer` function does more than simply create |
| 957 |
pointer instances, it has to create pointer *types* first. This is done with the |
| 958 |
:func:`POINTER` function, which accepts any :mod:`!ctypes` type, and returns a |
| 959 |
new type:: |
| 960 |
|
| 961 |
>>> PI = POINTER(c_int) |
| 962 |
>>> PI |
| 963 |
<class 'ctypes.LP_c_long'> |
| 964 |
>>> PI(42) |
| 965 |
Traceback (most recent call last): |
| 966 |
File "<stdin>", line 1, in <module> |
| 967 |
TypeError: expected c_long instead of int |
| 968 |
>>> PI(c_int(42)) |
| 969 |
<ctypes.LP_c_long object at 0x...> |
| 970 |
>>> |
| 971 |
|
| 972 |
Calling the pointer type without an argument creates a ``NULL`` pointer. |
| 973 |
``NULL`` pointers have a ``False`` boolean value:: |
| 974 |
|
| 975 |
>>> null_ptr = POINTER(c_int)() |
| 976 |
>>> print(bool(null_ptr)) |
| 977 |
False |
| 978 |
>>> |
| 979 |
|
| 980 |
:mod:`!ctypes` checks for ``NULL`` when dereferencing pointers (but dereferencing |
| 981 |
invalid non-\ ``NULL`` pointers would crash Python):: |
| 982 |
|
| 983 |
>>> null_ptr[0] |
| 984 |
Traceback (most recent call last): |
| 985 |
.... |
| 986 |
ValueError: NULL pointer access |
| 987 |
>>> |
| 988 |
|
| 989 |
>>> null_ptr[0] = 1234 |
| 990 |
Traceback (most recent call last): |
| 991 |
.... |
| 992 |
ValueError: NULL pointer access |
| 993 |
>>> |
| 994 |
|
| 995 |
.. _ctypes-thread-safety: |
| 996 |
|
| 997 |
Thread safety without the GIL |
| 998 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 999 |
|
| 1000 |
From Python 3.13 onward, the :term:`GIL` can be disabled on the :term:`free-threaded build`. |
| 1001 |
In ctypes, reads and writes to a single object concurrently is safe, but not across multiple objects: |
| 1002 |
|
| 1003 |
.. code-block:: pycon |
| 1004 |
|
| 1005 |
>>> number = c_int(42) |
| 1006 |
>>> pointer_a = pointer(number) |
| 1007 |
>>> pointer_b = pointer(number) |
| 1008 |
|
| 1009 |
In the above, it's only safe for one object to read and write to the address at once if the GIL is disabled. |
| 1010 |
So, ``pointer_a`` can be shared and written to across multiple threads, but only if ``pointer_b`` |
| 1011 |
is not also attempting to do the same. If this is an issue, consider using a :class:`threading.Lock` |
| 1012 |
to synchronize access to memory: |
| 1013 |
|
| 1014 |
.. code-block:: pycon |
| 1015 |
|
| 1016 |
>>> import threading |
| 1017 |
>>> lock = threading.Lock() |
| 1018 |
>>> # Thread 1 |
| 1019 |
>>> with lock: |
| 1020 |
... pointer_a.contents = 24 |
| 1021 |
>>> # Thread 2 |
| 1022 |
>>> with lock: |
| 1023 |
... pointer_b.contents = 42 |
| 1024 |
|
| 1025 |
|
| 1026 |
.. _ctypes-type-conversions: |
| 1027 |
|
| 1028 |
Type conversions |
| 1029 |
^^^^^^^^^^^^^^^^ |
| 1030 |
|
| 1031 |
Usually, ctypes does strict type checking. This means, if you have |
| 1032 |
``POINTER(c_int)`` in the :attr:`~_CFuncPtr.argtypes` list of a function or as the type of |
| 1033 |
a member field in a structure definition, only instances of exactly the same |
| 1034 |
type are accepted. There are some exceptions to this rule, where ctypes accepts |
| 1035 |
other objects. For example, you can pass compatible array instances instead of |
| 1036 |
pointer types. So, for ``POINTER(c_int)``, ctypes accepts an array of c_int:: |
| 1037 |
|
| 1038 |
>>> class Bar(Structure): |
| 1039 |
... _fields_ = [("count", c_int), ("values", POINTER(c_int))] |
| 1040 |
... |
| 1041 |
>>> bar = Bar() |
| 1042 |
>>> bar.values = (c_int * 3)(1, 2, 3) |
| 1043 |
>>> bar.count = 3 |
| 1044 |
>>> for i in range(bar.count): |
| 1045 |
... print(bar.values[i]) |
| 1046 |
... |
| 1047 |
1 |
| 1048 |
2 |
| 1049 |
3 |
| 1050 |
>>> |
| 1051 |
|
| 1052 |
In addition, if a function argument is explicitly declared to be a pointer type |
| 1053 |
(such as ``POINTER(c_int)``) in :attr:`~_CFuncPtr.argtypes`, an object of the pointed |
| 1054 |
type (``c_int`` in this case) can be passed to the function. ctypes will apply |
| 1055 |
the required :func:`byref` conversion in this case automatically. |
| 1056 |
|
| 1057 |
To set a POINTER type field to ``NULL``, you can assign ``None``:: |
| 1058 |
|
| 1059 |
>>> bar.values = None |
| 1060 |
>>> |
| 1061 |
|
| 1062 |
.. XXX list other conversions... |
| 1063 |
|
| 1064 |
Sometimes you have instances of incompatible types. In C, you can cast one type |
| 1065 |
into another type. :mod:`!ctypes` provides a :func:`cast` function which can be |
| 1066 |
used in the same way. The ``Bar`` structure defined above accepts |
| 1067 |
``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field, |
| 1068 |
but not instances of other types:: |
| 1069 |
|
| 1070 |
>>> bar.values = (c_byte * 4)() |
| 1071 |
Traceback (most recent call last): |
| 1072 |
File "<stdin>", line 1, in <module> |
| 1073 |
TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance |
| 1074 |
>>> |
| 1075 |
|
| 1076 |
For these cases, the :func:`cast` function is handy. |
| 1077 |
|
| 1078 |
The :func:`cast` function can be used to cast a ctypes instance into a pointer |
| 1079 |
to a different ctypes data type. :func:`cast` takes two parameters, a ctypes |
| 1080 |
object that is or can be converted to a pointer of some kind, and a ctypes |
| 1081 |
pointer type. It returns an instance of the second argument, which references |
| 1082 |
the same memory block as the first argument:: |
| 1083 |
|
| 1084 |
>>> a = (c_byte * 4)() |
| 1085 |
>>> cast(a, POINTER(c_int)) |
| 1086 |
<ctypes.LP_c_long object at ...> |
| 1087 |
>>> |
| 1088 |
|
| 1089 |
So, :func:`cast` can be used to assign to the ``values`` field of ``Bar`` the |
| 1090 |
structure:: |
| 1091 |
|
| 1092 |
>>> bar = Bar() |
| 1093 |
>>> bar.values = cast((c_byte * 4)(), POINTER(c_int)) |
| 1094 |
>>> print(bar.values[0]) |
| 1095 |
0 |
| 1096 |
>>> |
| 1097 |
|
| 1098 |
|
| 1099 |
.. _ctypes-incomplete-types: |
| 1100 |
|
| 1101 |
Incomplete Types |
| 1102 |
^^^^^^^^^^^^^^^^ |
| 1103 |
|
| 1104 |
*Incomplete Types* are structures, unions or arrays whose members are not yet |
| 1105 |
specified. In C, they are specified by forward declarations, which are defined |
| 1106 |
later:: |
| 1107 |
|
| 1108 |
struct cell; /* forward declaration */ |
| 1109 |
|
| 1110 |
struct cell { |
| 1111 |
char *name; |
| 1112 |
struct cell *next; |
| 1113 |
}; |
| 1114 |
|
| 1115 |
The straightforward translation into ctypes code would be this, but it does not |
| 1116 |
work:: |
| 1117 |
|
| 1118 |
>>> class cell(Structure): |
| 1119 |
... _fields_ = [("name", c_char_p), |
| 1120 |
... ("next", POINTER(cell))] |
| 1121 |
... |
| 1122 |
Traceback (most recent call last): |
| 1123 |
File "<stdin>", line 1, in <module> |
| 1124 |
File "<stdin>", line 2, in cell |
| 1125 |
NameError: name 'cell' is not defined |
| 1126 |
>>> |
| 1127 |
|
| 1128 |
because the new ``class cell`` is not available in the class statement itself. |
| 1129 |
In :mod:`!ctypes`, we can define the ``cell`` class and set the |
| 1130 |
:attr:`~Structure._fields_` attribute later, after the class statement:: |
| 1131 |
|
| 1132 |
>>> from ctypes import * |
| 1133 |
>>> class cell(Structure): |
| 1134 |
... pass |
| 1135 |
... |
| 1136 |
>>> cell._fields_ = [("name", c_char_p), |
| 1137 |
... ("next", POINTER(cell))] |
| 1138 |
>>> |
| 1139 |
|
| 1140 |
Let's try it. We create two instances of ``cell``, and let them point to each |
| 1141 |
other, and finally follow the pointer chain a few times:: |
| 1142 |
|
| 1143 |
>>> c1 = cell() |
| 1144 |
>>> c1.name = b"foo" |
| 1145 |
>>> c2 = cell() |
| 1146 |
>>> c2.name = b"bar" |
| 1147 |
>>> c1.next = pointer(c2) |
| 1148 |
>>> c2.next = pointer(c1) |
| 1149 |
>>> p = c1 |
| 1150 |
>>> for i in range(8): |
| 1151 |
... print(p.name, end=" ") |
| 1152 |
... p = p.next[0] |
| 1153 |
... |
| 1154 |
foo bar foo bar foo bar foo bar |
| 1155 |
>>> |
| 1156 |
|
| 1157 |
|
| 1158 |
.. _ctypes-callback-functions: |
| 1159 |
|
| 1160 |
Callback functions |
| 1161 |
^^^^^^^^^^^^^^^^^^ |
| 1162 |
|
| 1163 |
:mod:`!ctypes` allows creating C callable function pointers from Python callables. |
| 1164 |
These are sometimes called *callback functions*. |
| 1165 |
|
| 1166 |
First, you must create a class for the callback function. The class knows the |
| 1167 |
calling convention, the return type, and the number and types of arguments this |
| 1168 |
function will receive. |
| 1169 |
|
| 1170 |
The :func:`CFUNCTYPE` factory function creates types for callback functions |
| 1171 |
using the ``cdecl`` calling convention. On Windows, the :func:`WINFUNCTYPE` |
| 1172 |
factory function creates types for callback functions using the ``stdcall`` |
| 1173 |
calling convention. |
| 1174 |
|
| 1175 |
Both of these factory functions are called with the result type as first |
| 1176 |
argument, and the callback functions expected argument types as the remaining |
| 1177 |
arguments. |
| 1178 |
|
| 1179 |
I will present an example here which uses the standard C library's |
| 1180 |
:c:func:`!qsort` function, that is used to sort items with the help of a callback |
| 1181 |
function. :c:func:`!qsort` will be used to sort an array of integers:: |
| 1182 |
|
| 1183 |
>>> IntArray5 = c_int * 5 |
| 1184 |
>>> ia = IntArray5(5, 1, 7, 33, 99) |
| 1185 |
>>> qsort = libc.qsort |
| 1186 |
>>> qsort.restype = None |
| 1187 |
>>> |
| 1188 |
|
| 1189 |
:func:`!qsort` must be called with a pointer to the data to sort, the number of |
| 1190 |
items in the data array, the size of one item, and a pointer to the comparison |
| 1191 |
function, the callback. The callback will then be called with two pointers to |
| 1192 |
items, and it must return a negative integer if the first item is smaller than |
| 1193 |
the second, a zero if they are equal, and a positive integer otherwise. |
| 1194 |
|
| 1195 |
So our callback function receives pointers to integers, and must return an |
| 1196 |
integer. First we create the ``type`` for the callback function:: |
| 1197 |
|
| 1198 |
>>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int)) |
| 1199 |
>>> |
| 1200 |
|
| 1201 |
To get started, here is a simple callback that shows the values it gets |
| 1202 |
passed:: |
| 1203 |
|
| 1204 |
>>> def py_cmp_func(a, b): |
| 1205 |
... print("py_cmp_func", a[0], b[0]) |
| 1206 |
... return 0 |
| 1207 |
... |
| 1208 |
>>> cmp_func = CMPFUNC(py_cmp_func) |
| 1209 |
>>> |
| 1210 |
|
| 1211 |
The result:: |
| 1212 |
|
| 1213 |
>>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX |
| 1214 |
py_cmp_func 5 1 |
| 1215 |
py_cmp_func 33 99 |
| 1216 |
py_cmp_func 7 33 |
| 1217 |
py_cmp_func 5 7 |
| 1218 |
py_cmp_func 1 7 |
| 1219 |
>>> |
| 1220 |
|
| 1221 |
Now we can actually compare the two items and return a useful result:: |
| 1222 |
|
| 1223 |
>>> def py_cmp_func(a, b): |
| 1224 |
... print("py_cmp_func", a[0], b[0]) |
| 1225 |
... return a[0] - b[0] |
| 1226 |
... |
| 1227 |
>>> |
| 1228 |
>>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX |
| 1229 |
py_cmp_func 5 1 |
| 1230 |
py_cmp_func 33 99 |
| 1231 |
py_cmp_func 7 33 |
| 1232 |
py_cmp_func 1 7 |
| 1233 |
py_cmp_func 5 7 |
| 1234 |
>>> |
| 1235 |
|
| 1236 |
As we can easily check, our array is sorted now:: |
| 1237 |
|
| 1238 |
>>> for i in ia: print(i, end=" ") |
| 1239 |
... |
| 1240 |
1 5 7 33 99 |
| 1241 |
>>> |
| 1242 |
|
| 1243 |
The function factories can be used as decorator factories, so we may as well |
| 1244 |
write:: |
| 1245 |
|
| 1246 |
>>> @CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int)) |
| 1247 |
... def py_cmp_func(a, b): |
| 1248 |
... print("py_cmp_func", a[0], b[0]) |
| 1249 |
... return a[0] - b[0] |
| 1250 |
... |
| 1251 |
>>> qsort(ia, len(ia), sizeof(c_int), py_cmp_func) |
| 1252 |
py_cmp_func 5 1 |
| 1253 |
py_cmp_func 33 99 |
| 1254 |
py_cmp_func 7 33 |
| 1255 |
py_cmp_func 1 7 |
| 1256 |
py_cmp_func 5 7 |
| 1257 |
>>> |
| 1258 |
|
| 1259 |
.. note:: |
| 1260 |
|
| 1261 |
Make sure you keep references to :func:`CFUNCTYPE` objects as long as they |
| 1262 |
are used from C code. :mod:`!ctypes` doesn't, and if you don't, they may be |
| 1263 |
garbage collected, crashing your program when a callback is made. |
| 1264 |
|
| 1265 |
Also, note that if the callback function is called in a thread created |
| 1266 |
outside of Python's control (e.g. by the foreign code that calls the |
| 1267 |
callback), ctypes creates a new dummy Python thread on every invocation. This |
| 1268 |
behavior is correct for most purposes, but it means that values stored with |
| 1269 |
:class:`threading.local` will *not* survive across different callbacks, even when |
| 1270 |
those calls are made from the same C thread. |
| 1271 |
|
| 1272 |
.. _ctypes-accessing-values-exported-from-dlls: |
| 1273 |
|
| 1274 |
Accessing values exported from dlls |
| 1275 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1276 |
|
| 1277 |
Some shared libraries not only export functions, they also export variables. An |
| 1278 |
example in the Python library itself is the :c:data:`Py_Version`, Python |
| 1279 |
runtime version number encoded in a single constant integer. |
| 1280 |
|
| 1281 |
:mod:`!ctypes` can access values like this with the :meth:`~_CData.in_dll` class methods of |
| 1282 |
the type. *pythonapi* is a predefined symbol giving access to the Python C |
| 1283 |
api:: |
| 1284 |
|
| 1285 |
>>> version = ctypes.c_int.in_dll(ctypes.pythonapi, "Py_Version") |
| 1286 |
>>> print(hex(version.value)) |
| 1287 |
0x30c00a0 |
| 1288 |
|
| 1289 |
An extended example which also demonstrates the use of pointers accesses the |
| 1290 |
:c:data:`PyImport_FrozenModules` pointer exported by Python. |
| 1291 |
|
| 1292 |
Quoting the docs for that value: |
| 1293 |
|
| 1294 |
This pointer is initialized to point to an array of :c:struct:`_frozen` |
| 1295 |
records, terminated by one whose members are all ``NULL`` or zero. When a frozen |
| 1296 |
module is imported, it is searched in this table. Third-party code could play |
| 1297 |
tricks with this to provide a dynamically created collection of frozen modules. |
| 1298 |
|
| 1299 |
So manipulating this pointer could even prove useful. To restrict the example |
| 1300 |
size, we show only how this table can be read with :mod:`!ctypes`:: |
| 1301 |
|
| 1302 |
>>> from ctypes import * |
| 1303 |
>>> |
| 1304 |
>>> class struct_frozen(Structure): |
| 1305 |
... _fields_ = [("name", c_char_p), |
| 1306 |
... ("code", POINTER(c_ubyte)), |
| 1307 |
... ("size", c_int), |
| 1308 |
... ("get_code", POINTER(c_ubyte)), # Function pointer |
| 1309 |
... ] |
| 1310 |
... |
| 1311 |
>>> |
| 1312 |
|
| 1313 |
We have defined the :c:struct:`_frozen` data type, so we can get the pointer |
| 1314 |
to the table:: |
| 1315 |
|
| 1316 |
>>> FrozenTable = POINTER(struct_frozen) |
| 1317 |
>>> table = FrozenTable.in_dll(pythonapi, "_PyImport_FrozenBootstrap") |
| 1318 |
>>> |
| 1319 |
|
| 1320 |
Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we |
| 1321 |
can iterate over it, but we just have to make sure that our loop terminates, |
| 1322 |
because pointers have no size. Sooner or later it would probably crash with an |
| 1323 |
access violation or whatever, so it's better to break out of the loop when we |
| 1324 |
hit the ``NULL`` entry:: |
| 1325 |
|
| 1326 |
>>> for item in table: |
| 1327 |
... if item.name is None: |
| 1328 |
... break |
| 1329 |
... print(item.name.decode("ascii"), item.size) |
| 1330 |
... |
| 1331 |
_frozen_importlib 31764 |
| 1332 |
_frozen_importlib_external 41499 |
| 1333 |
zipimport 12345 |
| 1334 |
>>> |
| 1335 |
|
| 1336 |
The fact that standard Python has a frozen module and a frozen package |
| 1337 |
(indicated by the negative ``size`` member) is not well known, it is only used |
| 1338 |
for testing. Try it out with ``import __hello__`` for example. |
| 1339 |
|
| 1340 |
|
| 1341 |
.. _ctypes-surprises: |
| 1342 |
|
| 1343 |
Surprises |
| 1344 |
^^^^^^^^^ |
| 1345 |
|
| 1346 |
There are some edges in :mod:`!ctypes` where you might expect something other |
| 1347 |
than what actually happens. |
| 1348 |
|
| 1349 |
Consider the following example:: |
| 1350 |
|
| 1351 |
>>> from ctypes import * |
| 1352 |
>>> class POINT(Structure): |
| 1353 |
... _fields_ = ("x", c_int), ("y", c_int) |
| 1354 |
... |
| 1355 |
>>> class RECT(Structure): |
| 1356 |
... _fields_ = ("a", POINT), ("b", POINT) |
| 1357 |
... |
| 1358 |
>>> p1 = POINT(1, 2) |
| 1359 |
>>> p2 = POINT(3, 4) |
| 1360 |
>>> rc = RECT(p1, p2) |
| 1361 |
>>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y) |
| 1362 |
1 2 3 4 |
| 1363 |
>>> # now swap the two points |
| 1364 |
>>> rc.a, rc.b = rc.b, rc.a |
| 1365 |
>>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y) |
| 1366 |
3 4 3 4 |
| 1367 |
>>> |
| 1368 |
|
| 1369 |
Hm. We certainly expected the last statement to print ``3 4 1 2``. What |
| 1370 |
happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above:: |
| 1371 |
|
| 1372 |
>>> temp0, temp1 = rc.b, rc.a |
| 1373 |
>>> rc.a = temp0 |
| 1374 |
>>> rc.b = temp1 |
| 1375 |
>>> |
| 1376 |
|
| 1377 |
Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of |
| 1378 |
the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer |
| 1379 |
contents of ``temp0`` into ``rc`` 's buffer. This, in turn, changes the |
| 1380 |
contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have |
| 1381 |
the expected effect. |
| 1382 |
|
| 1383 |
Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays |
| 1384 |
doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing |
| 1385 |
the root-object's underlying buffer. |
| 1386 |
|
| 1387 |
Another example that may behave differently from what one would expect is this:: |
| 1388 |
|
| 1389 |
>>> s = c_char_p() |
| 1390 |
>>> s.value = b"abc def ghi" |
| 1391 |
>>> s.value |
| 1392 |
b'abc def ghi' |
| 1393 |
>>> s.value is s.value |
| 1394 |
False |
| 1395 |
>>> |
| 1396 |
|
| 1397 |
.. note:: |
| 1398 |
|
| 1399 |
Objects instantiated from :class:`c_char_p` can only have their value set to bytes |
| 1400 |
or integers. |
| 1401 |
|
| 1402 |
Why is it printing ``False``? ctypes instances are objects containing a memory |
| 1403 |
block plus some :term:`descriptor`\s accessing the contents of the memory. |
| 1404 |
Storing a Python object in the memory block does not store the object itself, |
| 1405 |
instead the ``contents`` of the object is stored. Accessing the contents again |
| 1406 |
constructs a new Python object each time! |
| 1407 |
|
| 1408 |
|
| 1409 |
.. _ctypes-variable-sized-data-types: |
| 1410 |
|
| 1411 |
Variable-sized data types |
| 1412 |
^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1413 |
|
| 1414 |
:mod:`!ctypes` provides some support for variable-sized arrays and structures. |
| 1415 |
|
| 1416 |
The :func:`resize` function can be used to resize the memory buffer of an |
| 1417 |
existing ctypes object. The function takes the object as first argument, and |
| 1418 |
the requested size in bytes as the second argument. The memory block cannot be |
| 1419 |
made smaller than the natural memory block specified by the objects type, a |
| 1420 |
:exc:`ValueError` is raised if this is tried:: |
| 1421 |
|
| 1422 |
>>> short_array = (c_short * 4)() |
| 1423 |
>>> print(sizeof(short_array)) |
| 1424 |
8 |
| 1425 |
>>> resize(short_array, 4) |
| 1426 |
Traceback (most recent call last): |
| 1427 |
... |
| 1428 |
ValueError: minimum size is 8 |
| 1429 |
>>> resize(short_array, 32) |
| 1430 |
>>> sizeof(short_array) |
| 1431 |
32 |
| 1432 |
>>> sizeof(type(short_array)) |
| 1433 |
8 |
| 1434 |
>>> |
| 1435 |
|
| 1436 |
This is nice and fine, but how would one access the additional elements |
| 1437 |
contained in this array? Since the type still only knows about 4 elements, we |
| 1438 |
get errors accessing other elements:: |
| 1439 |
|
| 1440 |
>>> short_array[:] |
| 1441 |
[0, 0, 0, 0] |
| 1442 |
>>> short_array[7] |
| 1443 |
Traceback (most recent call last): |
| 1444 |
... |
| 1445 |
IndexError: invalid index |
| 1446 |
>>> |
| 1447 |
|
| 1448 |
Another way to use variable-sized data types with :mod:`!ctypes` is to use the |
| 1449 |
dynamic nature of Python, and (re-)define the data type after the required size |
| 1450 |
is already known, on a case by case basis. |
| 1451 |
|
| 1452 |
|
| 1453 |
.. _ctypes-ctypes-reference: |
| 1454 |
|
| 1455 |
ctypes reference |
| 1456 |
---------------- |
| 1457 |
|
| 1458 |
|
| 1459 |
.. _ctypes-finding-shared-libraries: |
| 1460 |
|
| 1461 |
Finding shared libraries |
| 1462 |
^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1463 |
|
| 1464 |
When programming in a compiled language, shared libraries are accessed when |
| 1465 |
compiling/linking a program, and when the program is run. |
| 1466 |
|
| 1467 |
The purpose of the :func:`~ctypes.util.find_library` function is to locate a library in a way |
| 1468 |
similar to what the compiler or runtime loader does (on platforms with several |
| 1469 |
versions of a shared library the most recent should be loaded), while the ctypes |
| 1470 |
library loaders act like when a program is run, and call the runtime loader |
| 1471 |
directly. |
| 1472 |
|
| 1473 |
The :mod:`!ctypes.util` module provides a function which can help to determine |
| 1474 |
the library to load. |
| 1475 |
|
| 1476 |
|
| 1477 |
.. data:: find_library(name) |
| 1478 |
:module: ctypes.util |
| 1479 |
:noindex: |
| 1480 |
|
| 1481 |
Try to find a library and return a pathname. *name* is the library name without |
| 1482 |
any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this |
| 1483 |
is the form used for the posix linker option :option:`!-l`). If no library can |
| 1484 |
be found, returns ``None``. |
| 1485 |
|
| 1486 |
The exact functionality is system dependent. |
| 1487 |
|
| 1488 |
On Linux, :func:`~ctypes.util.find_library` tries to run external programs |
| 1489 |
(``/sbin/ldconfig``, ``gcc``, ``objdump`` and ``ld``) to find the library file. |
| 1490 |
It returns the filename of the library file. |
| 1491 |
|
| 1492 |
Note that if the output of these programs does not correspond to the dynamic |
| 1493 |
linker used by Python, the result of this function may be misleading. |
| 1494 |
|
| 1495 |
.. versionchanged:: 3.6 |
| 1496 |
On Linux, the value of the environment variable ``LD_LIBRARY_PATH`` is used |
| 1497 |
when searching for libraries, if a library cannot be found by any other means. |
| 1498 |
|
| 1499 |
Here are some examples:: |
| 1500 |
|
| 1501 |
>>> from ctypes.util import find_library |
| 1502 |
>>> find_library("m") |
| 1503 |
'libm.so.6' |
| 1504 |
>>> find_library("c") |
| 1505 |
'libc.so.6' |
| 1506 |
>>> find_library("bz2") |
| 1507 |
'libbz2.so.1.0' |
| 1508 |
>>> |
| 1509 |
|
| 1510 |
On macOS and Android, :func:`~ctypes.util.find_library` uses the system's |
| 1511 |
standard naming schemes and paths to locate the library, and returns a full |
| 1512 |
pathname if successful:: |
| 1513 |
|
| 1514 |
>>> from ctypes.util import find_library |
| 1515 |
>>> find_library("c") |
| 1516 |
'/usr/lib/libc.dylib' |
| 1517 |
>>> find_library("m") |
| 1518 |
'/usr/lib/libm.dylib' |
| 1519 |
>>> find_library("bz2") |
| 1520 |
'/usr/lib/libbz2.dylib' |
| 1521 |
>>> find_library("AGL") |
| 1522 |
'/System/Library/Frameworks/AGL.framework/AGL' |
| 1523 |
>>> |
| 1524 |
|
| 1525 |
On Windows, :func:`~ctypes.util.find_library` searches along the system search path, and |
| 1526 |
returns the full pathname, but since there is no predefined naming scheme a call |
| 1527 |
like ``find_library("c")`` will fail and return ``None``. |
| 1528 |
|
| 1529 |
If wrapping a shared library with :mod:`!ctypes`, it *may* be better to determine |
| 1530 |
the shared library name at development time, and hardcode that into the wrapper |
| 1531 |
module instead of using :func:`~ctypes.util.find_library` to locate the library at runtime. |
| 1532 |
|
| 1533 |
|
| 1534 |
.. _ctypes-listing-loaded-shared-libraries: |
| 1535 |
|
| 1536 |
Listing loaded shared libraries |
| 1537 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1538 |
|
| 1539 |
When writing code that relies on code loaded from shared libraries, it can be |
| 1540 |
useful to know which shared libraries have already been loaded into the current |
| 1541 |
process. |
| 1542 |
|
| 1543 |
The :mod:`!ctypes.util` module provides the :func:`~ctypes.util.dllist` function, |
| 1544 |
which calls the different APIs provided by the various platforms to help determine |
| 1545 |
which shared libraries have already been loaded into the current process. |
| 1546 |
|
| 1547 |
The exact output of this function will be system dependent. On most platforms, |
| 1548 |
the first entry of this list represents the current process itself, which may |
| 1549 |
be an empty string. |
| 1550 |
For example, on glibc-based Linux, the return may look like:: |
| 1551 |
|
| 1552 |
>>> from ctypes.util import dllist |
| 1553 |
>>> dllist() |
| 1554 |
['', 'linux-vdso.so.1', '/lib/x86_64-linux-gnu/libm.so.6', '/lib/x86_64-linux-gnu/libc.so.6', ... ] |
| 1555 |
|
| 1556 |
.. _ctypes-loading-shared-libraries: |
| 1557 |
|
| 1558 |
Loading shared libraries |
| 1559 |
^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1560 |
|
| 1561 |
There are several ways to load shared libraries into the Python process. One |
| 1562 |
way is to instantiate :py:class:`CDLL` or one of its subclasses: |
| 1563 |
|
| 1564 |
|
| 1565 |
.. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False, winmode=None) |
| 1566 |
|
| 1567 |
Represents a loaded shared library. |
| 1568 |
|
| 1569 |
Functions in this library use the standard C calling convention, and are |
| 1570 |
assumed to return :c:expr:`int`. |
| 1571 |
The Python :term:`global interpreter lock` is released before calling any |
| 1572 |
function exported by these libraries, and reacquired afterwards. |
| 1573 |
For different function behavior, use a subclass: :py:class:`~ctypes.OleDLL`, |
| 1574 |
:py:class:`~ctypes.WinDLL`, or :py:class:`~ctypes.PyDLL`. |
| 1575 |
|
| 1576 |
If you have an existing :py:attr:`handle <ctypes.CDLL._handle>` to an already |
| 1577 |
loaded shared library, it can be passed as the *handle* argument to wrap |
| 1578 |
the opened library in a new :py:class:`!CDLL` object. |
| 1579 |
In this case, *name* is only used to set the :py:attr:`~ctypes.CDLL._name` |
| 1580 |
attribute, but it may be adjusted and/or validated. |
| 1581 |
|
| 1582 |
If *handle* is ``None``, the underlying platform's :manpage:`dlopen(3)` or |
| 1583 |
:c:func:`!LoadLibrary` function is used to load the library into |
| 1584 |
the process, and to get a handle to it. |
| 1585 |
|
| 1586 |
*name* is the pathname of the shared library to open. |
| 1587 |
If *name* does not contain a path separator, the library is found |
| 1588 |
in a platform-specific way. |
| 1589 |
|
| 1590 |
On non-Windows systems, *name* can be ``None``. In this case, |
| 1591 |
:c:func:`!dlopen` is called with ``NULL``, which opens the main program |
| 1592 |
as a "library". |
| 1593 |
(Some systems do the same is *name* is empty; ``None``/``NULL`` is more |
| 1594 |
portable.) |
| 1595 |
|
| 1596 |
.. admonition:: CPython implementation detail |
| 1597 |
|
| 1598 |
Since CPython is linked to ``libc``, a ``None`` *name* is often used |
| 1599 |
to access the C standard library:: |
| 1600 |
|
| 1601 |
>>> printf = ctypes.CDLL(None).printf |
| 1602 |
>>> printf.argtypes = [ctypes.c_char_p] |
| 1603 |
>>> printf(b"hello\n") |
| 1604 |
hello |
| 1605 |
6 |
| 1606 |
|
| 1607 |
To access the Python C API, prefer :py:data:`ctypes.pythonapi` which |
| 1608 |
works across platforms. |
| 1609 |
|
| 1610 |
The *mode* parameter can be used to specify how the library is loaded. For |
| 1611 |
details, consult the :manpage:`dlopen(3)` manpage. On Windows, *mode* is |
| 1612 |
ignored. On posix systems, RTLD_NOW is always added, and is not |
| 1613 |
configurable. |
| 1614 |
|
| 1615 |
The *use_errno* parameter, when set to true, enables a ctypes mechanism that |
| 1616 |
allows accessing the system :data:`errno` error number in a safe way. |
| 1617 |
:mod:`!ctypes` maintains a thread-local copy of the system's :data:`errno` |
| 1618 |
variable; if you call foreign functions created with ``use_errno=True`` then the |
| 1619 |
:data:`errno` value before the function call is swapped with the ctypes private |
| 1620 |
copy, the same happens immediately after the function call. |
| 1621 |
|
| 1622 |
The function :func:`ctypes.get_errno` returns the value of the ctypes private |
| 1623 |
copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy |
| 1624 |
to a new value and returns the former value. |
| 1625 |
|
| 1626 |
The *use_last_error* parameter, when set to true, enables the same mechanism for |
| 1627 |
the Windows error code which is managed by the :func:`GetLastError` and |
| 1628 |
:func:`!SetLastError` Windows API functions; :func:`ctypes.get_last_error` and |
| 1629 |
:func:`ctypes.set_last_error` are used to request and change the ctypes private |
| 1630 |
copy of the windows error code. |
| 1631 |
|
| 1632 |
The *winmode* parameter is used on Windows to specify how the library is loaded |
| 1633 |
(since *mode* is ignored). It takes any value that is valid for the Win32 API |
| 1634 |
``LoadLibraryEx`` flags parameter. When omitted, the default is to use the |
| 1635 |
flags that result in the most secure DLL load, which avoids issues such as DLL |
| 1636 |
hijacking. Passing the full path to the DLL is the safest way to ensure the |
| 1637 |
correct library and dependencies are loaded. |
| 1638 |
|
| 1639 |
On Windows creating a :class:`CDLL` instance may fail even if the DLL name |
| 1640 |
exists. When a dependent DLL of the loaded DLL is not found, a |
| 1641 |
:exc:`OSError` error is raised with the message *"[WinError 126] The |
| 1642 |
specified module could not be found".* This error message does not contain |
| 1643 |
the name of the missing DLL because the Windows API does not return this |
| 1644 |
information making this error hard to diagnose. To resolve this error and |
| 1645 |
determine which DLL is not found, you need to find the list of dependent |
| 1646 |
DLLs and determine which one is not found using Windows debugging and |
| 1647 |
tracing tools. |
| 1648 |
|
| 1649 |
.. seealso:: |
| 1650 |
|
| 1651 |
`Microsoft DUMPBIN tool <https://learn.microsoft.com/en-us/cpp/build/reference/dumpbin-reference?view=msvc-170>`_ |
| 1652 |
-- A tool to find DLL dependents. |
| 1653 |
|
| 1654 |
.. versionchanged:: 3.8 |
| 1655 |
Added *winmode* parameter. |
| 1656 |
|
| 1657 |
.. versionchanged:: 3.12 |
| 1658 |
|
| 1659 |
The *name* parameter can now be a :term:`path-like object`. |
| 1660 |
|
| 1661 |
Instances of this class have no public methods. Functions exported by the |
| 1662 |
shared library can be accessed as attributes or by index. Please note that |
| 1663 |
accessing the function through an attribute caches the result and therefore |
| 1664 |
accessing it repeatedly returns the same object each time. On the other hand, |
| 1665 |
accessing it through an index returns a new object each time:: |
| 1666 |
|
| 1667 |
>>> from ctypes import CDLL |
| 1668 |
>>> libc = CDLL("libc.so.6") # On Linux |
| 1669 |
>>> libc.time == libc.time |
| 1670 |
True |
| 1671 |
>>> libc['time'] == libc['time'] |
| 1672 |
False |
| 1673 |
|
| 1674 |
The following public attributes are available. Their name starts with an |
| 1675 |
underscore to not clash with exported function names: |
| 1676 |
|
| 1677 |
.. attribute:: _handle |
| 1678 |
|
| 1679 |
The system handle used to access the library. |
| 1680 |
|
| 1681 |
.. attribute:: _name |
| 1682 |
|
| 1683 |
The name of the library passed in the constructor. |
| 1684 |
|
| 1685 |
.. class:: OleDLL |
| 1686 |
|
| 1687 |
See :py:class:`~ctypes.CDLL`, the superclass, for common information. |
| 1688 |
|
| 1689 |
Functions in this library use the ``stdcall`` calling convention, and are |
| 1690 |
assumed to return the windows specific :class:`HRESULT` code. :class:`HRESULT` |
| 1691 |
values contain information specifying whether the function call failed or |
| 1692 |
succeeded, together with additional error code. If the return value signals a |
| 1693 |
failure, an :class:`OSError` is automatically raised. |
| 1694 |
|
| 1695 |
.. availability:: Windows |
| 1696 |
|
| 1697 |
.. versionchanged:: 3.3 |
| 1698 |
:exc:`WindowsError` used to be raised, |
| 1699 |
which is now an alias of :exc:`OSError`. |
| 1700 |
|
| 1701 |
|
| 1702 |
.. class:: WinDLL |
| 1703 |
|
| 1704 |
See :py:class:`~ctypes.CDLL`, the superclass, for common information. |
| 1705 |
|
| 1706 |
Functions in these libraries use the ``stdcall`` calling convention, and are |
| 1707 |
assumed to return :c:expr:`int` by default. |
| 1708 |
|
| 1709 |
.. availability:: Windows |
| 1710 |
|
| 1711 |
.. class:: PyDLL |
| 1712 |
|
| 1713 |
See :py:class:`~ctypes.CDLL`, the superclass, for common information. |
| 1714 |
|
| 1715 |
When functions in this library are called, the |
| 1716 |
Python GIL is *not* released during the function call, and after the function |
| 1717 |
execution the Python error flag is checked. If the error flag is set, a Python |
| 1718 |
exception is raised. |
| 1719 |
|
| 1720 |
Thus, this is only useful to call Python C API functions directly. |
| 1721 |
|
| 1722 |
|
| 1723 |
.. data:: RTLD_GLOBAL |
| 1724 |
|
| 1725 |
Flag to use as *mode* parameter. On platforms where this flag is not available, |
| 1726 |
it is defined as the integer zero. |
| 1727 |
|
| 1728 |
|
| 1729 |
.. data:: RTLD_LOCAL |
| 1730 |
|
| 1731 |
Flag to use as *mode* parameter. On platforms where this is not available, it |
| 1732 |
is the same as *RTLD_GLOBAL*. |
| 1733 |
|
| 1734 |
|
| 1735 |
.. data:: DEFAULT_MODE |
| 1736 |
|
| 1737 |
The default mode which is used to load shared libraries. On OSX 10.3, this is |
| 1738 |
*RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*. |
| 1739 |
|
| 1740 |
|
| 1741 |
Shared libraries can also be loaded by using one of the prefabricated objects, |
| 1742 |
which are instances of the :class:`LibraryLoader` class, either by calling the |
| 1743 |
:meth:`~LibraryLoader.LoadLibrary` method, or by retrieving the library as |
| 1744 |
attribute of the loader instance. |
| 1745 |
|
| 1746 |
.. class:: LibraryLoader(dlltype) |
| 1747 |
|
| 1748 |
Class which loads shared libraries. *dlltype* should be one of the |
| 1749 |
:class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types. |
| 1750 |
|
| 1751 |
:meth:`!__getattr__` has special behavior: It allows loading a shared library by |
| 1752 |
accessing it as attribute of a library loader instance. The result is cached, |
| 1753 |
so repeated attribute accesses return the same library each time. |
| 1754 |
|
| 1755 |
.. method:: LoadLibrary(name) |
| 1756 |
|
| 1757 |
Load a shared library into the process and return it. This method always |
| 1758 |
returns a new instance of the library. |
| 1759 |
|
| 1760 |
|
| 1761 |
These prefabricated library loaders are available: |
| 1762 |
|
| 1763 |
.. data:: cdll |
| 1764 |
|
| 1765 |
Creates :class:`CDLL` instances. |
| 1766 |
|
| 1767 |
|
| 1768 |
.. data:: windll |
| 1769 |
|
| 1770 |
Creates :class:`WinDLL` instances. |
| 1771 |
|
| 1772 |
.. availability:: Windows |
| 1773 |
|
| 1774 |
|
| 1775 |
.. data:: oledll |
| 1776 |
|
| 1777 |
Creates :class:`OleDLL` instances. |
| 1778 |
|
| 1779 |
.. availability:: Windows |
| 1780 |
|
| 1781 |
|
| 1782 |
.. data:: pydll |
| 1783 |
|
| 1784 |
Creates :class:`PyDLL` instances. |
| 1785 |
|
| 1786 |
|
| 1787 |
For accessing the C Python api directly, a ready-to-use Python shared library |
| 1788 |
object is available: |
| 1789 |
|
| 1790 |
.. data:: pythonapi |
| 1791 |
|
| 1792 |
An instance of :class:`PyDLL` that exposes Python C API functions as |
| 1793 |
attributes. Note that all these functions are assumed to return C |
| 1794 |
:c:expr:`int`, which is of course not always the truth, so you have to assign |
| 1795 |
the correct :attr:`!restype` attribute to use these functions. |
| 1796 |
|
| 1797 |
.. audit-event:: ctypes.dlopen name ctypes.LibraryLoader |
| 1798 |
|
| 1799 |
Loading a library through any of these objects raises an |
| 1800 |
:ref:`auditing event <auditing>` ``ctypes.dlopen`` with string argument |
| 1801 |
``name``, the name used to load the library. |
| 1802 |
|
| 1803 |
.. audit-event:: ctypes.dlsym library,name ctypes.LibraryLoader |
| 1804 |
|
| 1805 |
Accessing a function on a loaded library raises an auditing event |
| 1806 |
``ctypes.dlsym`` with arguments ``library`` (the library object) and ``name`` |
| 1807 |
(the symbol's name as a string or integer). |
| 1808 |
|
| 1809 |
.. audit-event:: ctypes.dlsym/handle handle,name ctypes.LibraryLoader |
| 1810 |
|
| 1811 |
In cases when only the library handle is available rather than the object, |
| 1812 |
accessing a function raises an auditing event ``ctypes.dlsym/handle`` with |
| 1813 |
arguments ``handle`` (the raw library handle) and ``name``. |
| 1814 |
|
| 1815 |
.. _ctypes-foreign-functions: |
| 1816 |
|
| 1817 |
Foreign functions |
| 1818 |
^^^^^^^^^^^^^^^^^ |
| 1819 |
|
| 1820 |
As explained in the previous section, foreign functions can be accessed as |
| 1821 |
attributes of loaded shared libraries. The function objects created in this way |
| 1822 |
by default accept any number of arguments, accept any ctypes data instances as |
| 1823 |
arguments, and return the default result type specified by the library loader. |
| 1824 |
|
| 1825 |
They are instances of a private local class :class:`!_FuncPtr` (not exposed |
| 1826 |
in :mod:`!ctypes`) which inherits from the private :class:`_CFuncPtr` class: |
| 1827 |
|
| 1828 |
.. doctest:: |
| 1829 |
|
| 1830 |
>>> import ctypes |
| 1831 |
>>> lib = ctypes.CDLL(None) |
| 1832 |
>>> issubclass(lib._FuncPtr, ctypes._CFuncPtr) |
| 1833 |
True |
| 1834 |
>>> lib._FuncPtr is ctypes._CFuncPtr |
| 1835 |
False |
| 1836 |
|
| 1837 |
.. class:: _CFuncPtr |
| 1838 |
|
| 1839 |
Base class for C callable foreign functions. |
| 1840 |
|
| 1841 |
Instances of foreign functions are also C compatible data types; they |
| 1842 |
represent C function pointers. |
| 1843 |
|
| 1844 |
This behavior can be customized by assigning to special attributes of the |
| 1845 |
foreign function object. |
| 1846 |
|
| 1847 |
.. attribute:: restype |
| 1848 |
|
| 1849 |
Assign a ctypes type to specify the result type of the foreign function. |
| 1850 |
Use ``None`` for :c:expr:`void`, a function not returning anything. |
| 1851 |
|
| 1852 |
It is possible to assign a callable Python object that is not a ctypes |
| 1853 |
type, in this case the function is assumed to return a C :c:expr:`int`, and |
| 1854 |
the callable will be called with this integer, allowing further |
| 1855 |
processing or error checking. Using this is deprecated, for more flexible |
| 1856 |
post processing or error checking use a ctypes data type as |
| 1857 |
:attr:`!restype` and assign a callable to the :attr:`errcheck` attribute. |
| 1858 |
|
| 1859 |
.. attribute:: argtypes |
| 1860 |
|
| 1861 |
Assign a tuple of ctypes types to specify the argument types that the |
| 1862 |
function accepts. Functions using the ``stdcall`` calling convention can |
| 1863 |
only be called with the same number of arguments as the length of this |
| 1864 |
tuple; functions using the C calling convention accept additional, |
| 1865 |
unspecified arguments as well. |
| 1866 |
|
| 1867 |
When a foreign function is called, each actual argument is passed to the |
| 1868 |
:meth:`~_CData.from_param` class method of the items in the :attr:`argtypes` |
| 1869 |
tuple, this method allows adapting the actual argument to an object that |
| 1870 |
the foreign function accepts. For example, a :class:`c_char_p` item in |
| 1871 |
the :attr:`argtypes` tuple will convert a string passed as argument into |
| 1872 |
a bytes object using ctypes conversion rules. |
| 1873 |
|
| 1874 |
New: It is now possible to put items in argtypes which are not ctypes |
| 1875 |
types, but each item must have a :meth:`~_CData.from_param` method which returns a |
| 1876 |
value usable as argument (integer, string, ctypes instance). This allows |
| 1877 |
defining adapters that can adapt custom objects as function parameters. |
| 1878 |
|
| 1879 |
.. attribute:: errcheck |
| 1880 |
|
| 1881 |
Assign a Python function or another callable to this attribute. The |
| 1882 |
callable will be called with three or more arguments: |
| 1883 |
|
| 1884 |
.. function:: callable(result, func, arguments) |
| 1885 |
:noindex: |
| 1886 |
:module: |
| 1887 |
|
| 1888 |
*result* is what the foreign function returns, as specified by the |
| 1889 |
:attr:`!restype` attribute. |
| 1890 |
|
| 1891 |
*func* is the foreign function object itself, this allows reusing the |
| 1892 |
same callable object to check or post process the results of several |
| 1893 |
functions. |
| 1894 |
|
| 1895 |
*arguments* is a tuple containing the parameters originally passed to |
| 1896 |
the function call, this allows specializing the behavior on the |
| 1897 |
arguments used. |
| 1898 |
|
| 1899 |
The object that this function returns will be returned from the |
| 1900 |
foreign function call, but it can also check the result value |
| 1901 |
and raise an exception if the foreign function call failed. |
| 1902 |
|
| 1903 |
|
| 1904 |
.. audit-event:: ctypes.set_exception code foreign-functions |
| 1905 |
|
| 1906 |
On Windows, when a foreign function call raises a system exception (for |
| 1907 |
example, due to an access violation), it will be captured and replaced with |
| 1908 |
a suitable Python exception. Further, an auditing event |
| 1909 |
``ctypes.set_exception`` with argument ``code`` will be raised, allowing an |
| 1910 |
audit hook to replace the exception with its own. |
| 1911 |
|
| 1912 |
.. audit-event:: ctypes.call_function func_pointer,arguments foreign-functions |
| 1913 |
|
| 1914 |
Some ways to invoke foreign function calls as well as some of the |
| 1915 |
functions in this module may raise an auditing event |
| 1916 |
``ctypes.call_function`` with arguments ``function pointer`` and ``arguments``. |
| 1917 |
|
| 1918 |
.. _ctypes-function-prototypes: |
| 1919 |
|
| 1920 |
Function prototypes |
| 1921 |
^^^^^^^^^^^^^^^^^^^ |
| 1922 |
|
| 1923 |
Foreign functions can also be created by instantiating function prototypes. |
| 1924 |
Function prototypes are similar to function prototypes in C; they describe a |
| 1925 |
function (return type, argument types, calling convention) without defining an |
| 1926 |
implementation. The factory functions must be called with the desired result |
| 1927 |
type and the argument types of the function, and can be used as decorator |
| 1928 |
factories, and as such, be applied to functions through the ``@wrapper`` syntax. |
| 1929 |
See :ref:`ctypes-callback-functions` for examples. |
| 1930 |
|
| 1931 |
|
| 1932 |
.. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False) |
| 1933 |
|
| 1934 |
The returned function prototype creates functions that use the standard C |
| 1935 |
calling convention. The function will release the GIL during the call. If |
| 1936 |
*use_errno* is set to true, the ctypes private copy of the system |
| 1937 |
:data:`errno` variable is exchanged with the real :data:`errno` value before |
| 1938 |
and after the call; *use_last_error* does the same for the Windows error |
| 1939 |
code. |
| 1940 |
|
| 1941 |
|
| 1942 |
.. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False) |
| 1943 |
|
| 1944 |
The returned function prototype creates functions that use the |
| 1945 |
``stdcall`` calling convention. The function will |
| 1946 |
release the GIL during the call. *use_errno* and *use_last_error* have the |
| 1947 |
same meaning as above. |
| 1948 |
|
| 1949 |
.. availability:: Windows |
| 1950 |
|
| 1951 |
|
| 1952 |
.. function:: PYFUNCTYPE(restype, *argtypes) |
| 1953 |
|
| 1954 |
The returned function prototype creates functions that use the Python calling |
| 1955 |
convention. The function will *not* release the GIL during the call. |
| 1956 |
|
| 1957 |
Function prototypes created by these factory functions can be instantiated in |
| 1958 |
different ways, depending on the type and number of the parameters in the call: |
| 1959 |
|
| 1960 |
.. function:: prototype(address) |
| 1961 |
:noindex: |
| 1962 |
:module: |
| 1963 |
|
| 1964 |
Returns a foreign function at the specified address which must be an integer. |
| 1965 |
|
| 1966 |
|
| 1967 |
.. function:: prototype(callable) |
| 1968 |
:noindex: |
| 1969 |
:module: |
| 1970 |
|
| 1971 |
Create a C callable function (a callback function) from a Python *callable*. |
| 1972 |
|
| 1973 |
|
| 1974 |
.. function:: prototype(func_spec[, paramflags]) |
| 1975 |
:noindex: |
| 1976 |
:module: |
| 1977 |
|
| 1978 |
Returns a foreign function exported by a shared library. *func_spec* must |
| 1979 |
be a 2-tuple ``(name_or_ordinal, library)``. The first item is the name of |
| 1980 |
the exported function as string, or the ordinal of the exported function |
| 1981 |
as small integer. The second item is the shared library instance. |
| 1982 |
|
| 1983 |
|
| 1984 |
.. function:: prototype(vtbl_index, name[, paramflags[, iid]]) |
| 1985 |
:noindex: |
| 1986 |
:module: |
| 1987 |
|
| 1988 |
Returns a foreign function that will call a COM method. *vtbl_index* is |
| 1989 |
the index into the virtual function table, a small non-negative |
| 1990 |
integer. *name* is name of the COM method. *iid* is an optional pointer to |
| 1991 |
the interface identifier which is used in extended error reporting. |
| 1992 |
|
| 1993 |
If *iid* is not specified, an :exc:`OSError` is raised if the COM method |
| 1994 |
call fails. If *iid* is specified, a :exc:`~ctypes.COMError` is raised |
| 1995 |
instead. |
| 1996 |
|
| 1997 |
COM methods use a special calling convention: They require a pointer to |
| 1998 |
the COM interface as first argument, in addition to those parameters that |
| 1999 |
are specified in the :attr:`!argtypes` tuple. |
| 2000 |
|
| 2001 |
.. availability:: Windows |
| 2002 |
|
| 2003 |
|
| 2004 |
The optional *paramflags* parameter creates foreign function wrappers with much |
| 2005 |
more functionality than the features described above. |
| 2006 |
|
| 2007 |
*paramflags* must be a tuple of the same length as :attr:`~_CFuncPtr.argtypes`. |
| 2008 |
|
| 2009 |
Each item in this tuple contains further information about a parameter, it must |
| 2010 |
be a tuple containing one, two, or three items. |
| 2011 |
|
| 2012 |
The first item is an integer containing a combination of direction |
| 2013 |
flags for the parameter: |
| 2014 |
|
| 2015 |
1 |
| 2016 |
Specifies an input parameter to the function. |
| 2017 |
|
| 2018 |
2 |
| 2019 |
Output parameter. The foreign function fills in a value. |
| 2020 |
|
| 2021 |
4 |
| 2022 |
Input parameter which defaults to the integer zero. |
| 2023 |
|
| 2024 |
The optional second item is the parameter name as string. If this is specified, |
| 2025 |
the foreign function can be called with named parameters. |
| 2026 |
|
| 2027 |
The optional third item is the default value for this parameter. |
| 2028 |
|
| 2029 |
|
| 2030 |
The following example demonstrates how to wrap the Windows ``MessageBoxW`` function so |
| 2031 |
that it supports default parameters and named arguments. The C declaration from |
| 2032 |
the windows header file is this:: |
| 2033 |
|
| 2034 |
WINUSERAPI int WINAPI |
| 2035 |
MessageBoxW( |
| 2036 |
HWND hWnd, |
| 2037 |
LPCWSTR lpText, |
| 2038 |
LPCWSTR lpCaption, |
| 2039 |
UINT uType); |
| 2040 |
|
| 2041 |
Here is the wrapping with :mod:`!ctypes`:: |
| 2042 |
|
| 2043 |
>>> from ctypes import c_int, WINFUNCTYPE, windll |
| 2044 |
>>> from ctypes.wintypes import HWND, LPCWSTR, UINT |
| 2045 |
>>> prototype = WINFUNCTYPE(c_int, HWND, LPCWSTR, LPCWSTR, UINT) |
| 2046 |
>>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", "Hello from ctypes"), (1, "flags", 0) |
| 2047 |
>>> MessageBox = prototype(("MessageBoxW", windll.user32), paramflags) |
| 2048 |
|
| 2049 |
The ``MessageBox`` foreign function can now be called in these ways:: |
| 2050 |
|
| 2051 |
>>> MessageBox() |
| 2052 |
>>> MessageBox(text="Spam, spam, spam") |
| 2053 |
>>> MessageBox(flags=2, text="foo bar") |
| 2054 |
|
| 2055 |
A second example demonstrates output parameters. The win32 ``GetWindowRect`` |
| 2056 |
function retrieves the dimensions of a specified window by copying them into |
| 2057 |
``RECT`` structure that the caller has to supply. Here is the C declaration:: |
| 2058 |
|
| 2059 |
WINUSERAPI BOOL WINAPI |
| 2060 |
GetWindowRect( |
| 2061 |
HWND hWnd, |
| 2062 |
LPRECT lpRect); |
| 2063 |
|
| 2064 |
Here is the wrapping with :mod:`!ctypes`:: |
| 2065 |
|
| 2066 |
>>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError |
| 2067 |
>>> from ctypes.wintypes import BOOL, HWND, RECT |
| 2068 |
>>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT)) |
| 2069 |
>>> paramflags = (1, "hwnd"), (2, "lprect") |
| 2070 |
>>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags) |
| 2071 |
>>> |
| 2072 |
|
| 2073 |
Functions with output parameters will automatically return the output parameter |
| 2074 |
value if there is a single one, or a tuple containing the output parameter |
| 2075 |
values when there are more than one, so the GetWindowRect function now returns a |
| 2076 |
RECT instance, when called. |
| 2077 |
|
| 2078 |
Output parameters can be combined with the :attr:`~_CFuncPtr.errcheck` protocol to do |
| 2079 |
further output processing and error checking. The win32 ``GetWindowRect`` api |
| 2080 |
function returns a ``BOOL`` to signal success or failure, so this function could |
| 2081 |
do the error checking, and raises an exception when the api call failed:: |
| 2082 |
|
| 2083 |
>>> def errcheck(result, func, args): |
| 2084 |
... if not result: |
| 2085 |
... raise WinError() |
| 2086 |
... return args |
| 2087 |
... |
| 2088 |
>>> GetWindowRect.errcheck = errcheck |
| 2089 |
>>> |
| 2090 |
|
| 2091 |
If the :attr:`~_CFuncPtr.errcheck` function returns the argument tuple it receives |
| 2092 |
unchanged, :mod:`!ctypes` continues the normal processing it does on the output |
| 2093 |
parameters. If you want to return a tuple of window coordinates instead of a |
| 2094 |
``RECT`` instance, you can retrieve the fields in the function and return them |
| 2095 |
instead, the normal processing will no longer take place:: |
| 2096 |
|
| 2097 |
>>> def errcheck(result, func, args): |
| 2098 |
... if not result: |
| 2099 |
... raise WinError() |
| 2100 |
... rc = args[1] |
| 2101 |
... return rc.left, rc.top, rc.bottom, rc.right |
| 2102 |
... |
| 2103 |
>>> GetWindowRect.errcheck = errcheck |
| 2104 |
>>> |
| 2105 |
|
| 2106 |
|
| 2107 |
.. _ctypes-utility-functions: |
| 2108 |
|
| 2109 |
Utility functions |
| 2110 |
^^^^^^^^^^^^^^^^^ |
| 2111 |
|
| 2112 |
.. function:: addressof(obj) |
| 2113 |
|
| 2114 |
Returns the address of the memory buffer as integer. *obj* must be an |
| 2115 |
instance of a ctypes type. |
| 2116 |
|
| 2117 |
.. audit-event:: ctypes.addressof obj ctypes.addressof |
| 2118 |
|
| 2119 |
|
| 2120 |
.. function:: alignment(obj_or_type) |
| 2121 |
|
| 2122 |
Returns the alignment requirements of a ctypes type. *obj_or_type* must be a |
| 2123 |
ctypes type or instance. |
| 2124 |
|
| 2125 |
|
| 2126 |
.. function:: byref(obj[, offset]) |
| 2127 |
|
| 2128 |
Returns a light-weight pointer to *obj*, which must be an instance of a |
| 2129 |
ctypes type. *offset* defaults to zero, and must be an integer that will be |
| 2130 |
added to the internal pointer value. |
| 2131 |
|
| 2132 |
``byref(obj, offset)`` corresponds to this C code:: |
| 2133 |
|
| 2134 |
(((char *)&obj) + offset) |
| 2135 |
|
| 2136 |
The returned object can only be used as a foreign function call parameter. |
| 2137 |
It behaves similar to ``pointer(obj)``, but the construction is a lot faster. |
| 2138 |
|
| 2139 |
|
| 2140 |
.. function:: CopyComPointer(src, dst) |
| 2141 |
|
| 2142 |
Copies a COM pointer from *src* to *dst* and returns the Windows specific |
| 2143 |
:c:type:`!HRESULT` value. |
| 2144 |
|
| 2145 |
If *src* is not ``NULL``, its ``AddRef`` method is called, incrementing the |
| 2146 |
reference count. |
| 2147 |
|
| 2148 |
In contrast, the reference count of *dst* will not be decremented before |
| 2149 |
assigning the new value. Unless *dst* is ``NULL``, the caller is responsible |
| 2150 |
for decrementing the reference count by calling its ``Release`` method when |
| 2151 |
necessary. |
| 2152 |
|
| 2153 |
.. availability:: Windows |
| 2154 |
|
| 2155 |
.. versionadded:: 3.14 |
| 2156 |
|
| 2157 |
|
| 2158 |
.. function:: cast(obj, type) |
| 2159 |
|
| 2160 |
This function is similar to the cast operator in C. It returns a new instance |
| 2161 |
of *type* which points to the same memory block as *obj*. *type* must be a |
| 2162 |
pointer type, and *obj* must be an object that can be interpreted as a |
| 2163 |
pointer. |
| 2164 |
|
| 2165 |
|
| 2166 |
.. function:: create_string_buffer(init, size=None) |
| 2167 |
create_string_buffer(size) |
| 2168 |
|
| 2169 |
This function creates a mutable character buffer. The returned object is a |
| 2170 |
ctypes array of :class:`c_char`. |
| 2171 |
|
| 2172 |
If *size* is given (and not ``None``), it must be an :class:`int`. |
| 2173 |
It specifies the size of the returned array. |
| 2174 |
|
| 2175 |
If the *init* argument is given, it must be :class:`bytes`. It is used |
| 2176 |
to initialize the array items. Bytes not initialized this way are |
| 2177 |
set to zero (NUL). |
| 2178 |
|
| 2179 |
If *size* is not given (or if it is ``None``), the buffer is made one element |
| 2180 |
larger than *init*, effectively adding a NUL terminator. |
| 2181 |
|
| 2182 |
If both arguments are given, *size* must not be less than ``len(init)``. |
| 2183 |
|
| 2184 |
.. warning:: |
| 2185 |
|
| 2186 |
If *size* is equal to ``len(init)``, a NUL terminator is |
| 2187 |
not added. Do not treat such a buffer as a C string. |
| 2188 |
|
| 2189 |
For example:: |
| 2190 |
|
| 2191 |
>>> bytes(create_string_buffer(2)) |
| 2192 |
b'\x00\x00' |
| 2193 |
>>> bytes(create_string_buffer(b'ab')) |
| 2194 |
b'ab\x00' |
| 2195 |
>>> bytes(create_string_buffer(b'ab', 2)) |
| 2196 |
b'ab' |
| 2197 |
>>> bytes(create_string_buffer(b'ab', 4)) |
| 2198 |
b'ab\x00\x00' |
| 2199 |
>>> bytes(create_string_buffer(b'abcdef', 2)) |
| 2200 |
Traceback (most recent call last): |
| 2201 |
... |
| 2202 |
ValueError: byte string too long |
| 2203 |
|
| 2204 |
.. audit-event:: ctypes.create_string_buffer init,size ctypes.create_string_buffer |
| 2205 |
|
| 2206 |
|
| 2207 |
.. function:: create_unicode_buffer(init, size=None) |
| 2208 |
create_unicode_buffer(size) |
| 2209 |
|
| 2210 |
This function creates a mutable unicode character buffer. The returned object is |
| 2211 |
a ctypes array of :class:`c_wchar`. |
| 2212 |
|
| 2213 |
The function takes the same arguments as :func:`~create_string_buffer` except |
| 2214 |
*init* must be a string and *size* counts :class:`c_wchar`. |
| 2215 |
|
| 2216 |
.. audit-event:: ctypes.create_unicode_buffer init,size ctypes.create_unicode_buffer |
| 2217 |
|
| 2218 |
|
| 2219 |
.. function:: DllCanUnloadNow() |
| 2220 |
|
| 2221 |
This function is a hook which allows implementing in-process |
| 2222 |
COM servers with ctypes. It is called from the DllCanUnloadNow function that |
| 2223 |
the _ctypes extension dll exports. |
| 2224 |
|
| 2225 |
.. availability:: Windows |
| 2226 |
|
| 2227 |
|
| 2228 |
.. function:: DllGetClassObject() |
| 2229 |
|
| 2230 |
This function is a hook which allows implementing in-process |
| 2231 |
COM servers with ctypes. It is called from the DllGetClassObject function |
| 2232 |
that the ``_ctypes`` extension dll exports. |
| 2233 |
|
| 2234 |
.. availability:: Windows |
| 2235 |
|
| 2236 |
|
| 2237 |
.. function:: find_library(name) |
| 2238 |
:module: ctypes.util |
| 2239 |
|
| 2240 |
Try to find a library and return a pathname. *name* is the library name |
| 2241 |
without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version |
| 2242 |
number (this is the form used for the posix linker option :option:`!-l`). If |
| 2243 |
no library can be found, returns ``None``. |
| 2244 |
|
| 2245 |
The exact functionality is system dependent. |
| 2246 |
|
| 2247 |
See :ref:`ctypes-finding-shared-libraries` for complete documentation. |
| 2248 |
|
| 2249 |
|
| 2250 |
.. function:: find_msvcrt() |
| 2251 |
:module: ctypes.util |
| 2252 |
|
| 2253 |
Returns the filename of the VC runtime library used by Python, |
| 2254 |
and by the extension modules. If the name of the library cannot be |
| 2255 |
determined, ``None`` is returned. |
| 2256 |
|
| 2257 |
If you need to free memory, for example, allocated by an extension module |
| 2258 |
with a call to the ``free(void *)``, it is important that you use the |
| 2259 |
function in the same library that allocated the memory. |
| 2260 |
|
| 2261 |
.. availability:: Windows |
| 2262 |
|
| 2263 |
|
| 2264 |
.. function:: dllist() |
| 2265 |
:module: ctypes.util |
| 2266 |
|
| 2267 |
Try to provide a list of paths of the shared libraries loaded into the current |
| 2268 |
process. These paths are not normalized or processed in any way. The function |
| 2269 |
can raise :exc:`OSError` if the underlying platform APIs fail. |
| 2270 |
The exact functionality is system dependent. |
| 2271 |
|
| 2272 |
On most platforms, the first element of the list represents the current |
| 2273 |
executable file. It may be an empty string. |
| 2274 |
|
| 2275 |
.. availability:: Windows, macOS, iOS, glibc, BSD libc, musl |
| 2276 |
.. versionadded:: 3.14 |
| 2277 |
|
| 2278 |
.. function:: FormatError([code]) |
| 2279 |
|
| 2280 |
Returns a textual description of the error code *code*. If no error code is |
| 2281 |
specified, the last error code is used by calling the Windows API function |
| 2282 |
:func:`GetLastError`. |
| 2283 |
|
| 2284 |
.. availability:: Windows |
| 2285 |
|
| 2286 |
|
| 2287 |
.. function:: GetLastError() |
| 2288 |
|
| 2289 |
Returns the last error code set by Windows in the calling thread. |
| 2290 |
This function calls the Windows ``GetLastError()`` function directly, |
| 2291 |
it does not return the ctypes-private copy of the error code. |
| 2292 |
|
| 2293 |
.. availability:: Windows |
| 2294 |
|
| 2295 |
|
| 2296 |
.. function:: get_errno() |
| 2297 |
|
| 2298 |
Returns the current value of the ctypes-private copy of the system |
| 2299 |
:data:`errno` variable in the calling thread. |
| 2300 |
|
| 2301 |
.. audit-event:: ctypes.get_errno "" ctypes.get_errno |
| 2302 |
|
| 2303 |
.. function:: get_last_error() |
| 2304 |
|
| 2305 |
Returns the current value of the ctypes-private copy of the system |
| 2306 |
:data:`!LastError` variable in the calling thread. |
| 2307 |
|
| 2308 |
.. availability:: Windows |
| 2309 |
|
| 2310 |
.. audit-event:: ctypes.get_last_error "" ctypes.get_last_error |
| 2311 |
|
| 2312 |
|
| 2313 |
.. function:: memmove(dst, src, count) |
| 2314 |
|
| 2315 |
Same as the standard C memmove library function: copies *count* bytes from |
| 2316 |
*src* to *dst*. *dst* and *src* must be integers or ctypes instances that can |
| 2317 |
be converted to pointers. |
| 2318 |
|
| 2319 |
|
| 2320 |
.. function:: memset(dst, c, count) |
| 2321 |
|
| 2322 |
Same as the standard C memset library function: fills the memory block at |
| 2323 |
address *dst* with *count* bytes of value *c*. *dst* must be an integer |
| 2324 |
specifying an address, or a ctypes instance. |
| 2325 |
|
| 2326 |
|
| 2327 |
.. function:: POINTER(type, /) |
| 2328 |
|
| 2329 |
Create or return a ctypes pointer type. Pointer types are cached and |
| 2330 |
reused internally, so calling this function repeatedly is cheap. |
| 2331 |
*type* must be a ctypes type. |
| 2332 |
|
| 2333 |
.. impl-detail:: |
| 2334 |
|
| 2335 |
The resulting pointer type is cached in the ``__pointer_type__`` |
| 2336 |
attribute of *type*. |
| 2337 |
It is possible to set this attribute before the first call to |
| 2338 |
``POINTER`` in order to set a custom pointer type. |
| 2339 |
However, doing this is discouraged: manually creating a suitable |
| 2340 |
pointer type is difficult without relying on implementation |
| 2341 |
details that may change in future Python versions. |
| 2342 |
|
| 2343 |
|
| 2344 |
.. function:: pointer(obj, /) |
| 2345 |
|
| 2346 |
Create a new pointer instance, pointing to *obj*. |
| 2347 |
The returned object is of the type ``POINTER(type(obj))``. |
| 2348 |
|
| 2349 |
Note: If you just want to pass a pointer to an object to a foreign function |
| 2350 |
call, you should use ``byref(obj)`` which is much faster. |
| 2351 |
|
| 2352 |
|
| 2353 |
.. function:: resize(obj, size) |
| 2354 |
|
| 2355 |
This function resizes the internal memory buffer of *obj*, which must be an |
| 2356 |
instance of a ctypes type. It is not possible to make the buffer smaller |
| 2357 |
than the native size of the objects type, as given by ``sizeof(type(obj))``, |
| 2358 |
but it is possible to enlarge the buffer. |
| 2359 |
|
| 2360 |
|
| 2361 |
.. function:: set_errno(value) |
| 2362 |
|
| 2363 |
Set the current value of the ctypes-private copy of the system :data:`errno` |
| 2364 |
variable in the calling thread to *value* and return the previous value. |
| 2365 |
|
| 2366 |
.. audit-event:: ctypes.set_errno errno ctypes.set_errno |
| 2367 |
|
| 2368 |
|
| 2369 |
.. function:: set_last_error(value) |
| 2370 |
|
| 2371 |
Sets the current value of the ctypes-private copy of the system |
| 2372 |
:data:`!LastError` variable in the calling thread to *value* and return the |
| 2373 |
previous value. |
| 2374 |
|
| 2375 |
.. availability:: Windows |
| 2376 |
|
| 2377 |
.. audit-event:: ctypes.set_last_error error ctypes.set_last_error |
| 2378 |
|
| 2379 |
|
| 2380 |
.. function:: sizeof(obj_or_type) |
| 2381 |
|
| 2382 |
Returns the size in bytes of a ctypes type or instance memory buffer. |
| 2383 |
Does the same as the C ``sizeof`` operator. |
| 2384 |
|
| 2385 |
|
| 2386 |
.. function:: string_at(ptr, size=-1) |
| 2387 |
|
| 2388 |
Return the byte string at *void \*ptr*. |
| 2389 |
If *size* is specified, it is used as size, otherwise the string is assumed |
| 2390 |
to be zero-terminated. |
| 2391 |
|
| 2392 |
.. audit-event:: ctypes.string_at ptr,size ctypes.string_at |
| 2393 |
|
| 2394 |
|
| 2395 |
.. function:: WinError(code=None, descr=None) |
| 2396 |
|
| 2397 |
Creates an instance of :exc:`OSError`. If *code* is not specified, |
| 2398 |
:func:`GetLastError` is called to determine the error code. If *descr* is not |
| 2399 |
specified, :func:`FormatError` is called to get a textual description of the |
| 2400 |
error. |
| 2401 |
|
| 2402 |
.. availability:: Windows |
| 2403 |
|
| 2404 |
.. versionchanged:: 3.3 |
| 2405 |
An instance of :exc:`WindowsError` used to be created, which is now an |
| 2406 |
alias of :exc:`OSError`. |
| 2407 |
|
| 2408 |
|
| 2409 |
.. function:: wstring_at(ptr, size=-1) |
| 2410 |
|
| 2411 |
Return the wide-character string at *void \*ptr*. |
| 2412 |
If *size* is specified, it is used as the number of |
| 2413 |
characters of the string, otherwise the string is assumed to be |
| 2414 |
zero-terminated. |
| 2415 |
|
| 2416 |
.. audit-event:: ctypes.wstring_at ptr,size ctypes.wstring_at |
| 2417 |
|
| 2418 |
|
| 2419 |
.. function:: memoryview_at(ptr, size, readonly=False) |
| 2420 |
|
| 2421 |
Return a :class:`memoryview` object of length *size* that references memory |
| 2422 |
starting at *void \*ptr*. |
| 2423 |
|
| 2424 |
If *readonly* is true, the returned :class:`!memoryview` object can |
| 2425 |
not be used to modify the underlying memory. |
| 2426 |
(Changes made by other means will still be reflected in the returned |
| 2427 |
object.) |
| 2428 |
|
| 2429 |
This function is similar to :func:`string_at` with the key |
| 2430 |
difference of not making a copy of the specified memory. |
| 2431 |
It is a semantically equivalent (but more efficient) alternative to |
| 2432 |
``memoryview((c_byte * size).from_address(ptr))``. |
| 2433 |
(While :meth:`~_CData.from_address` only takes integers, *ptr* can also |
| 2434 |
be given as a :class:`ctypes.POINTER` or a :func:`~ctypes.byref` object.) |
| 2435 |
|
| 2436 |
.. audit-event:: ctypes.memoryview_at address,size,readonly |
| 2437 |
|
| 2438 |
.. versionadded:: 3.14 |
| 2439 |
|
| 2440 |
|
| 2441 |
.. _ctypes-data-types: |
| 2442 |
|
| 2443 |
Data types |
| 2444 |
^^^^^^^^^^ |
| 2445 |
|
| 2446 |
|
| 2447 |
.. class:: _CData |
| 2448 |
|
| 2449 |
This non-public class is the common base class of all ctypes data types. |
| 2450 |
Among other things, all ctypes type instances contain a memory block that |
| 2451 |
hold C compatible data; the address of the memory block is returned by the |
| 2452 |
:func:`addressof` helper function. Another instance variable is exposed as |
| 2453 |
:attr:`_objects`; this contains other Python objects that need to be kept |
| 2454 |
alive in case the memory block contains pointers. |
| 2455 |
|
| 2456 |
Common methods of ctypes data types, these are all class methods (to be |
| 2457 |
exact, they are methods of the :term:`metaclass`): |
| 2458 |
|
| 2459 |
.. method:: _CData.from_buffer(source[, offset]) |
| 2460 |
|
| 2461 |
This method returns a ctypes instance that shares the buffer of the |
| 2462 |
*source* object. The *source* object must support the writeable buffer |
| 2463 |
interface. The optional *offset* parameter specifies an offset into the |
| 2464 |
source buffer in bytes; the default is zero. If the source buffer is not |
| 2465 |
large enough a :exc:`ValueError` is raised. |
| 2466 |
|
| 2467 |
.. audit-event:: ctypes.cdata/buffer pointer,size,offset ctypes._CData.from_buffer |
| 2468 |
|
| 2469 |
.. method:: _CData.from_buffer_copy(source[, offset]) |
| 2470 |
|
| 2471 |
This method creates a ctypes instance, copying the buffer from the |
| 2472 |
*source* object buffer which must be readable. The optional *offset* |
| 2473 |
parameter specifies an offset into the source buffer in bytes; the default |
| 2474 |
is zero. If the source buffer is not large enough a :exc:`ValueError` is |
| 2475 |
raised. |
| 2476 |
|
| 2477 |
.. audit-event:: ctypes.cdata/buffer pointer,size,offset ctypes._CData.from_buffer_copy |
| 2478 |
|
| 2479 |
.. method:: from_address(address) |
| 2480 |
|
| 2481 |
This method returns a ctypes type instance using the memory specified by |
| 2482 |
*address* which must be an integer. |
| 2483 |
|
| 2484 |
.. audit-event:: ctypes.cdata address ctypes._CData.from_address |
| 2485 |
|
| 2486 |
This method, and others that indirectly call this method, raises an |
| 2487 |
:ref:`auditing event <auditing>` ``ctypes.cdata`` with argument |
| 2488 |
``address``. |
| 2489 |
|
| 2490 |
.. method:: from_param(obj) |
| 2491 |
|
| 2492 |
This method adapts *obj* to a ctypes type. It is called with the actual |
| 2493 |
object used in a foreign function call when the type is present in the |
| 2494 |
foreign function's :attr:`~_CFuncPtr.argtypes` tuple; |
| 2495 |
it must return an object that can be used as a function call parameter. |
| 2496 |
|
| 2497 |
All ctypes data types have a default implementation of this classmethod |
| 2498 |
that normally returns *obj* if that is an instance of the type. Some |
| 2499 |
types accept other objects as well. |
| 2500 |
|
| 2501 |
.. method:: in_dll(library, name) |
| 2502 |
|
| 2503 |
This method returns a ctypes type instance exported by a shared |
| 2504 |
library. *name* is the name of the symbol that exports the data, *library* |
| 2505 |
is the loaded shared library. |
| 2506 |
|
| 2507 |
Common class variables of ctypes data types: |
| 2508 |
|
| 2509 |
.. attribute:: __pointer_type__ |
| 2510 |
|
| 2511 |
The pointer type that was created by calling |
| 2512 |
:func:`POINTER` for corresponding ctypes data type. If a pointer type |
| 2513 |
was not yet created, the attribute is missing. |
| 2514 |
|
| 2515 |
.. versionadded:: 3.14 |
| 2516 |
|
| 2517 |
Common instance variables of ctypes data types: |
| 2518 |
|
| 2519 |
.. attribute:: _b_base_ |
| 2520 |
|
| 2521 |
Sometimes ctypes data instances do not own the memory block they contain, |
| 2522 |
instead they share part of the memory block of a base object. The |
| 2523 |
:attr:`_b_base_` read-only member is the root ctypes object that owns the |
| 2524 |
memory block. |
| 2525 |
|
| 2526 |
.. attribute:: _b_needsfree_ |
| 2527 |
|
| 2528 |
This read-only variable is true when the ctypes data instance has |
| 2529 |
allocated the memory block itself, false otherwise. |
| 2530 |
|
| 2531 |
.. attribute:: _objects |
| 2532 |
|
| 2533 |
This member is either ``None`` or a dictionary containing Python objects |
| 2534 |
that need to be kept alive so that the memory block contents is kept |
| 2535 |
valid. This object is only exposed for debugging; never modify the |
| 2536 |
contents of this dictionary. |
| 2537 |
|
| 2538 |
|
| 2539 |
.. _ctypes-fundamental-data-types-2: |
| 2540 |
|
| 2541 |
Fundamental data types |
| 2542 |
^^^^^^^^^^^^^^^^^^^^^^ |
| 2543 |
|
| 2544 |
.. class:: _SimpleCData |
| 2545 |
|
| 2546 |
This non-public class is the base class of all fundamental ctypes data |
| 2547 |
types. It is mentioned here because it contains the common attributes of the |
| 2548 |
fundamental ctypes data types. :class:`_SimpleCData` is a subclass of |
| 2549 |
:class:`_CData`, so it inherits their methods and attributes. ctypes data |
| 2550 |
types that are not and do not contain pointers can now be pickled. |
| 2551 |
|
| 2552 |
Instances have a single attribute: |
| 2553 |
|
| 2554 |
.. attribute:: value |
| 2555 |
|
| 2556 |
This attribute contains the actual value of the instance. For integer and |
| 2557 |
pointer types, it is an integer, for character types, it is a single |
| 2558 |
character bytes object or string, for character pointer types it is a |
| 2559 |
Python bytes object or string. |
| 2560 |
|
| 2561 |
When the ``value`` attribute is retrieved from a ctypes instance, usually |
| 2562 |
a new object is returned each time. :mod:`!ctypes` does *not* implement |
| 2563 |
original object return, always a new object is constructed. The same is |
| 2564 |
true for all other ctypes object instances. |
| 2565 |
|
| 2566 |
Each subclass has a class attribute: |
| 2567 |
|
| 2568 |
.. attribute:: _type_ |
| 2569 |
|
| 2570 |
Class attribute that contains an internal type code, as a |
| 2571 |
single-character string. |
| 2572 |
See :ref:`ctypes-fundamental-data-types` for a summary. |
| 2573 |
|
| 2574 |
Types marked \* in the summary may be (or always are) aliases of a |
| 2575 |
different :class:`_SimpleCData` subclass, and will not necessarily |
| 2576 |
use the listed type code. |
| 2577 |
For example, if the platform's :c:expr:`long`, :c:expr:`long long` |
| 2578 |
and :c:expr:`time_t` C types are the same, then :class:`c_long`, |
| 2579 |
:class:`c_longlong` and :class:`c_time_t` all refer to a single class, |
| 2580 |
:class:`c_long`, whose :attr:`_type_` code is ``'l'``. |
| 2581 |
The ``'L'`` code will be unused. |
| 2582 |
|
| 2583 |
.. seealso:: |
| 2584 |
|
| 2585 |
The :mod:`array` and :ref:`struct <format-characters>` modules, |
| 2586 |
as well as third-party modules like `numpy <https://numpy.org/doc/stable/reference/arrays.interface.html#object.__array_interface__>`__, |
| 2587 |
use similar -- but slightly different -- type codes. |
| 2588 |
|
| 2589 |
|
| 2590 |
Fundamental data types, when returned as foreign function call results, or, for |
| 2591 |
example, by retrieving structure field members or array items, are transparently |
| 2592 |
converted to native Python types. In other words, if a foreign function has a |
| 2593 |
:attr:`~_CFuncPtr.restype` of :class:`c_char_p`, you will always receive a Python bytes |
| 2594 |
object, *not* a :class:`c_char_p` instance. |
| 2595 |
|
| 2596 |
.. XXX above is false, it actually returns a Unicode string |
| 2597 |
|
| 2598 |
Subclasses of fundamental data types do *not* inherit this behavior. So, if a |
| 2599 |
foreign functions :attr:`!restype` is a subclass of :class:`c_void_p`, you will |
| 2600 |
receive an instance of this subclass from the function call. Of course, you can |
| 2601 |
get the value of the pointer by accessing the ``value`` attribute. |
| 2602 |
|
| 2603 |
These are the fundamental ctypes data types: |
| 2604 |
|
| 2605 |
.. class:: c_byte |
| 2606 |
|
| 2607 |
Represents the C :c:expr:`signed char` datatype, and interprets the value as |
| 2608 |
small integer. The constructor accepts an optional integer initializer; no |
| 2609 |
overflow checking is done. |
| 2610 |
|
| 2611 |
|
| 2612 |
.. class:: c_char |
| 2613 |
|
| 2614 |
Represents the C :c:expr:`char` datatype, and interprets the value as a single |
| 2615 |
character. The constructor accepts an optional string initializer, the |
| 2616 |
length of the string must be exactly one character. |
| 2617 |
|
| 2618 |
|
| 2619 |
.. class:: c_char_p |
| 2620 |
|
| 2621 |
Represents the C :c:expr:`char *` datatype when it points to a zero-terminated |
| 2622 |
string. For a general character pointer that may also point to binary data, |
| 2623 |
``POINTER(c_char)`` must be used. The constructor accepts an integer |
| 2624 |
address, or a bytes object. |
| 2625 |
|
| 2626 |
|
| 2627 |
.. class:: c_double |
| 2628 |
|
| 2629 |
Represents the C :c:expr:`double` datatype. The constructor accepts an |
| 2630 |
optional float initializer. |
| 2631 |
|
| 2632 |
|
| 2633 |
.. class:: c_longdouble |
| 2634 |
|
| 2635 |
Represents the C :c:expr:`long double` datatype. The constructor accepts an |
| 2636 |
optional float initializer. On platforms where ``sizeof(long double) == |
| 2637 |
sizeof(double)`` it is an alias to :class:`c_double`. |
| 2638 |
|
| 2639 |
.. class:: c_float |
| 2640 |
|
| 2641 |
Represents the C :c:expr:`float` datatype. The constructor accepts an |
| 2642 |
optional float initializer. |
| 2643 |
|
| 2644 |
|
| 2645 |
.. class:: c_double_complex |
| 2646 |
|
| 2647 |
Represents the C :c:expr:`double complex` datatype, if available. The |
| 2648 |
constructor accepts an optional :class:`complex` initializer. |
| 2649 |
|
| 2650 |
.. versionadded:: 3.14 |
| 2651 |
|
| 2652 |
|
| 2653 |
.. class:: c_float_complex |
| 2654 |
|
| 2655 |
Represents the C :c:expr:`float complex` datatype, if available. The |
| 2656 |
constructor accepts an optional :class:`complex` initializer. |
| 2657 |
|
| 2658 |
.. versionadded:: 3.14 |
| 2659 |
|
| 2660 |
|
| 2661 |
.. class:: c_longdouble_complex |
| 2662 |
|
| 2663 |
Represents the C :c:expr:`long double complex` datatype, if available. The |
| 2664 |
constructor accepts an optional :class:`complex` initializer. |
| 2665 |
|
| 2666 |
.. versionadded:: 3.14 |
| 2667 |
|
| 2668 |
|
| 2669 |
.. class:: c_int |
| 2670 |
|
| 2671 |
Represents the C :c:expr:`signed int` datatype. The constructor accepts an |
| 2672 |
optional integer initializer; no overflow checking is done. On platforms |
| 2673 |
where ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`. |
| 2674 |
|
| 2675 |
|
| 2676 |
.. class:: c_int8 |
| 2677 |
|
| 2678 |
Represents the C 8-bit :c:expr:`signed int` datatype. It is an alias for |
| 2679 |
:class:`c_byte`. |
| 2680 |
|
| 2681 |
|
| 2682 |
.. class:: c_int16 |
| 2683 |
|
| 2684 |
Represents the C 16-bit :c:expr:`signed int` datatype. Usually an alias for |
| 2685 |
:class:`c_short`. |
| 2686 |
|
| 2687 |
|
| 2688 |
.. class:: c_int32 |
| 2689 |
|
| 2690 |
Represents the C 32-bit :c:expr:`signed int` datatype. Usually an alias for |
| 2691 |
:class:`c_int`. |
| 2692 |
|
| 2693 |
|
| 2694 |
.. class:: c_int64 |
| 2695 |
|
| 2696 |
Represents the C 64-bit :c:expr:`signed int` datatype. Usually an alias for |
| 2697 |
:class:`c_longlong`. |
| 2698 |
|
| 2699 |
|
| 2700 |
.. class:: c_long |
| 2701 |
|
| 2702 |
Represents the C :c:expr:`signed long` datatype. The constructor accepts an |
| 2703 |
optional integer initializer; no overflow checking is done. |
| 2704 |
|
| 2705 |
|
| 2706 |
.. class:: c_longlong |
| 2707 |
|
| 2708 |
Represents the C :c:expr:`signed long long` datatype. The constructor accepts |
| 2709 |
an optional integer initializer; no overflow checking is done. |
| 2710 |
On platforms where ``sizeof(long long) == sizeof(long)`` it is an alias |
| 2711 |
to :class:`c_long`. |
| 2712 |
|
| 2713 |
|
| 2714 |
.. class:: c_short |
| 2715 |
|
| 2716 |
Represents the C :c:expr:`signed short` datatype. The constructor accepts an |
| 2717 |
optional integer initializer; no overflow checking is done. |
| 2718 |
|
| 2719 |
|
| 2720 |
.. class:: c_size_t |
| 2721 |
|
| 2722 |
Represents the C :c:type:`size_t` datatype. |
| 2723 |
Usually an alias for another unsigned integer type. |
| 2724 |
|
| 2725 |
|
| 2726 |
.. class:: c_ssize_t |
| 2727 |
|
| 2728 |
Represents the :c:type:`Py_ssize_t` datatype. |
| 2729 |
This is a signed version of :c:type:`size_t`; |
| 2730 |
that is, the POSIX :c:type:`ssize_t` type. |
| 2731 |
Usually an alias for another integer type. |
| 2732 |
|
| 2733 |
.. versionadded:: 3.2 |
| 2734 |
|
| 2735 |
|
| 2736 |
.. class:: c_time_t |
| 2737 |
|
| 2738 |
Represents the C :c:type:`time_t` datatype. |
| 2739 |
Usually an alias for another integer type. |
| 2740 |
|
| 2741 |
.. versionadded:: 3.12 |
| 2742 |
|
| 2743 |
|
| 2744 |
.. class:: c_ubyte |
| 2745 |
|
| 2746 |
Represents the C :c:expr:`unsigned char` datatype, it interprets the value as |
| 2747 |
small integer. The constructor accepts an optional integer initializer; no |
| 2748 |
overflow checking is done. |
| 2749 |
|
| 2750 |
|
| 2751 |
.. class:: c_uint |
| 2752 |
|
| 2753 |
Represents the C :c:expr:`unsigned int` datatype. The constructor accepts an |
| 2754 |
optional integer initializer; no overflow checking is done. On platforms |
| 2755 |
where ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`. |
| 2756 |
|
| 2757 |
|
| 2758 |
.. class:: c_uint8 |
| 2759 |
|
| 2760 |
Represents the C 8-bit :c:expr:`unsigned int` datatype. It is an alias for |
| 2761 |
:class:`c_ubyte`. |
| 2762 |
|
| 2763 |
|
| 2764 |
.. class:: c_uint16 |
| 2765 |
|
| 2766 |
Represents the C 16-bit :c:expr:`unsigned int` datatype. Usually an alias for |
| 2767 |
:class:`c_ushort`. |
| 2768 |
|
| 2769 |
|
| 2770 |
.. class:: c_uint32 |
| 2771 |
|
| 2772 |
Represents the C 32-bit :c:expr:`unsigned int` datatype. Usually an alias for |
| 2773 |
:class:`c_uint`. |
| 2774 |
|
| 2775 |
|
| 2776 |
.. class:: c_uint64 |
| 2777 |
|
| 2778 |
Represents the C 64-bit :c:expr:`unsigned int` datatype. Usually an alias for |
| 2779 |
:class:`c_ulonglong`. |
| 2780 |
|
| 2781 |
|
| 2782 |
.. class:: c_ulong |
| 2783 |
|
| 2784 |
Represents the C :c:expr:`unsigned long` datatype. The constructor accepts an |
| 2785 |
optional integer initializer; no overflow checking is done. |
| 2786 |
|
| 2787 |
|
| 2788 |
.. class:: c_ulonglong |
| 2789 |
|
| 2790 |
Represents the C :c:expr:`unsigned long long` datatype. The constructor |
| 2791 |
accepts an optional integer initializer; no overflow checking is done. |
| 2792 |
On platforms where ``sizeof(long long) == sizeof(long)`` it is an alias |
| 2793 |
to :class:`c_long`. |
| 2794 |
|
| 2795 |
|
| 2796 |
.. class:: c_ushort |
| 2797 |
|
| 2798 |
Represents the C :c:expr:`unsigned short` datatype. The constructor accepts |
| 2799 |
an optional integer initializer; no overflow checking is done. |
| 2800 |
|
| 2801 |
|
| 2802 |
.. class:: c_void_p |
| 2803 |
|
| 2804 |
Represents the C :c:expr:`void *` type. The value is represented as integer. |
| 2805 |
The constructor accepts an optional integer initializer. |
| 2806 |
|
| 2807 |
|
| 2808 |
.. class:: c_wchar |
| 2809 |
|
| 2810 |
Represents the C :c:type:`wchar_t` datatype, and interprets the value as a |
| 2811 |
single character unicode string. The constructor accepts an optional string |
| 2812 |
initializer, the length of the string must be exactly one character. |
| 2813 |
|
| 2814 |
|
| 2815 |
.. class:: c_wchar_p |
| 2816 |
|
| 2817 |
Represents the C :c:expr:`wchar_t *` datatype, which must be a pointer to a |
| 2818 |
zero-terminated wide character string. The constructor accepts an integer |
| 2819 |
address, or a string. |
| 2820 |
|
| 2821 |
|
| 2822 |
.. class:: c_bool |
| 2823 |
|
| 2824 |
Represent the C :c:expr:`bool` datatype (more accurately, :c:expr:`_Bool` from |
| 2825 |
C99). Its value can be ``True`` or ``False``, and the constructor accepts any object |
| 2826 |
that has a truth value. |
| 2827 |
|
| 2828 |
|
| 2829 |
.. class:: HRESULT |
| 2830 |
|
| 2831 |
Represents a :c:type:`!HRESULT` value, which contains success or |
| 2832 |
error information for a function or method call. |
| 2833 |
|
| 2834 |
.. availability:: Windows |
| 2835 |
|
| 2836 |
|
| 2837 |
.. class:: py_object |
| 2838 |
|
| 2839 |
Represents the C :c:expr:`PyObject *` datatype. Calling this without an |
| 2840 |
argument creates a ``NULL`` :c:expr:`PyObject *` pointer. |
| 2841 |
|
| 2842 |
.. versionchanged:: 3.14 |
| 2843 |
:class:`!py_object` is now a :term:`generic type`. |
| 2844 |
|
| 2845 |
.. _ctypes-wintypes: |
| 2846 |
|
| 2847 |
The :mod:`!ctypes.wintypes` module provides quite some other Windows specific |
| 2848 |
data types, for example :c:type:`!HWND`, :c:type:`!WPARAM`, |
| 2849 |
:c:type:`!VARIANT_BOOL` or :c:type:`!DWORD`. |
| 2850 |
Some useful structures like :c:type:`!MSG` or :c:type:`!RECT` are also defined. |
| 2851 |
|
| 2852 |
|
| 2853 |
.. _ctypes-structured-data-types: |
| 2854 |
|
| 2855 |
Structured data types |
| 2856 |
^^^^^^^^^^^^^^^^^^^^^ |
| 2857 |
|
| 2858 |
|
| 2859 |
.. class:: Union(*args, **kw) |
| 2860 |
|
| 2861 |
Abstract base class for unions in native byte order. |
| 2862 |
|
| 2863 |
Unions share common attributes and behavior with structures; |
| 2864 |
see :class:`Structure` documentation for details. |
| 2865 |
|
| 2866 |
.. class:: BigEndianUnion(*args, **kw) |
| 2867 |
|
| 2868 |
Abstract base class for unions in *big endian* byte order. |
| 2869 |
|
| 2870 |
.. versionadded:: 3.11 |
| 2871 |
|
| 2872 |
.. class:: LittleEndianUnion(*args, **kw) |
| 2873 |
|
| 2874 |
Abstract base class for unions in *little endian* byte order. |
| 2875 |
|
| 2876 |
.. versionadded:: 3.11 |
| 2877 |
|
| 2878 |
.. class:: BigEndianStructure(*args, **kw) |
| 2879 |
|
| 2880 |
Abstract base class for structures in *big endian* byte order. |
| 2881 |
|
| 2882 |
|
| 2883 |
.. class:: LittleEndianStructure(*args, **kw) |
| 2884 |
|
| 2885 |
Abstract base class for structures in *little endian* byte order. |
| 2886 |
|
| 2887 |
Structures and unions with non-native byte order cannot contain pointer type |
| 2888 |
fields, or any other data types containing pointer type fields. |
| 2889 |
|
| 2890 |
|
| 2891 |
.. class:: Structure(*args, **kw) |
| 2892 |
|
| 2893 |
Abstract base class for structures in *native* byte order. |
| 2894 |
|
| 2895 |
Concrete structure and union types must be created by subclassing one of these |
| 2896 |
types, and at least define a :attr:`_fields_` class variable. :mod:`!ctypes` will |
| 2897 |
create :term:`descriptor`\s which allow reading and writing the fields by direct |
| 2898 |
attribute accesses. These are the |
| 2899 |
|
| 2900 |
|
| 2901 |
.. attribute:: _fields_ |
| 2902 |
|
| 2903 |
A sequence defining the structure fields. The items must be 2-tuples or |
| 2904 |
3-tuples. The first item is the name of the field, the second item |
| 2905 |
specifies the type of the field; it can be any ctypes data type. |
| 2906 |
|
| 2907 |
For integer type fields like :class:`c_int`, a third optional item can be |
| 2908 |
given. It must be a small positive integer defining the bit width of the |
| 2909 |
field. |
| 2910 |
|
| 2911 |
Field names must be unique within one structure or union. This is not |
| 2912 |
checked, only one field can be accessed when names are repeated. |
| 2913 |
|
| 2914 |
It is possible to define the :attr:`_fields_` class variable *after* the |
| 2915 |
class statement that defines the Structure subclass, this allows creating |
| 2916 |
data types that directly or indirectly reference themselves:: |
| 2917 |
|
| 2918 |
class List(Structure): |
| 2919 |
pass |
| 2920 |
List._fields_ = [("pnext", POINTER(List)), |
| 2921 |
... |
| 2922 |
] |
| 2923 |
|
| 2924 |
The :attr:`!_fields_` class variable can only be set once. |
| 2925 |
Later assignments will raise an :exc:`AttributeError`. |
| 2926 |
|
| 2927 |
Additionally, the :attr:`!_fields_` class variable must be defined before |
| 2928 |
the structure or union type is first used: an instance or subclass is |
| 2929 |
created, :func:`sizeof` is called on it, and so on. |
| 2930 |
Later assignments to :attr:`!_fields_` will raise an :exc:`AttributeError`. |
| 2931 |
If :attr:`!_fields_` has not been set before such use, |
| 2932 |
the structure or union will have no own fields, as if :attr:`!_fields_` |
| 2933 |
was empty. |
| 2934 |
|
| 2935 |
Sub-subclasses of structure types inherit the fields of the base class |
| 2936 |
plus the :attr:`_fields_` defined in the sub-subclass, if any. |
| 2937 |
|
| 2938 |
|
| 2939 |
.. attribute:: _pack_ |
| 2940 |
|
| 2941 |
An optional small integer that allows overriding the alignment of |
| 2942 |
structure fields in the instance. |
| 2943 |
|
| 2944 |
This is only implemented for the MSVC-compatible memory layout |
| 2945 |
(see :attr:`_layout_`). |
| 2946 |
|
| 2947 |
Setting :attr:`!_pack_` to 0 is the same as not setting it at all. |
| 2948 |
Otherwise, the value must be a positive power of two. |
| 2949 |
The effect is equivalent to ``#pragma pack(N)`` in C, except |
| 2950 |
:mod:`!ctypes` may allow larger *n* than what the compiler accepts. |
| 2951 |
|
| 2952 |
:attr:`!_pack_` must already be defined |
| 2953 |
when :attr:`_fields_` is assigned, otherwise it will have no effect. |
| 2954 |
|
| 2955 |
.. deprecated-removed:: 3.14 3.19 |
| 2956 |
|
| 2957 |
For historical reasons, if :attr:`!_pack_` is non-zero, |
| 2958 |
the MSVC-compatible layout will be used by default. |
| 2959 |
On non-Windows platforms, this default is deprecated and is slated to |
| 2960 |
become an error in Python 3.19. |
| 2961 |
If it is intended, set :attr:`~Structure._layout_` to ``'ms'`` |
| 2962 |
explicitly. |
| 2963 |
|
| 2964 |
.. attribute:: _align_ |
| 2965 |
|
| 2966 |
An optional small integer that allows increasing the alignment of |
| 2967 |
the structure when being packed or unpacked to/from memory. |
| 2968 |
|
| 2969 |
The value must not be negative. |
| 2970 |
The effect is equivalent to ``__attribute__((aligned(N)))`` on GCC |
| 2971 |
or ``#pragma align(N)`` on MSVC, except :mod:`!ctypes` may allow |
| 2972 |
values that the compiler would reject. |
| 2973 |
|
| 2974 |
:attr:`!_align_` can only *increase* a structure's alignment |
| 2975 |
requirements. Setting it to 0 or 1 has no effect. |
| 2976 |
|
| 2977 |
Using values that are not powers of two is discouraged and may lead to |
| 2978 |
surprising behavior. |
| 2979 |
|
| 2980 |
:attr:`!_align_` must already be defined |
| 2981 |
when :attr:`_fields_` is assigned, otherwise it will have no effect. |
| 2982 |
|
| 2983 |
.. versionadded:: 3.13 |
| 2984 |
|
| 2985 |
.. attribute:: _layout_ |
| 2986 |
|
| 2987 |
An optional string naming the struct/union layout. It can currently |
| 2988 |
be set to: |
| 2989 |
|
| 2990 |
- ``"ms"``: the layout used by the Microsoft compiler (MSVC). |
| 2991 |
On GCC and Clang, this layout can be selected with |
| 2992 |
``__attribute__((ms_struct))``. |
| 2993 |
- ``"gcc-sysv"``: the layout used by GCC with the System V or “SysV-like” |
| 2994 |
data model, as used on Linux and macOS. |
| 2995 |
With this layout, :attr:`~Structure._pack_` must be unset or zero. |
| 2996 |
|
| 2997 |
If not set explicitly, ``ctypes`` will use a default that |
| 2998 |
matches the platform conventions. This default may change in future |
| 2999 |
Python releases (for example, when a new platform gains official support, |
| 3000 |
or when a difference between similar platforms is found). |
| 3001 |
Currently the default will be: |
| 3002 |
|
| 3003 |
- On Windows: ``"ms"`` |
| 3004 |
- When :attr:`~Structure._pack_` is specified: ``"ms"``. |
| 3005 |
(This is deprecated; see :attr:`~Structure._pack_` documentation.) |
| 3006 |
- Otherwise: ``"gcc-sysv"`` |
| 3007 |
|
| 3008 |
:attr:`!_layout_` must already be defined when |
| 3009 |
:attr:`~Structure._fields_` is assigned, otherwise it will have no effect. |
| 3010 |
|
| 3011 |
.. versionadded:: 3.14 |
| 3012 |
|
| 3013 |
.. attribute:: _anonymous_ |
| 3014 |
|
| 3015 |
An optional sequence that lists the names of unnamed (anonymous) fields. |
| 3016 |
:attr:`_anonymous_` must be already defined when :attr:`_fields_` is |
| 3017 |
assigned, otherwise it will have no effect. |
| 3018 |
|
| 3019 |
The fields listed in this variable must be structure or union type fields. |
| 3020 |
:mod:`!ctypes` will create descriptors in the structure type that allows |
| 3021 |
accessing the nested fields directly, without the need to create the |
| 3022 |
structure or union field. |
| 3023 |
|
| 3024 |
Here is an example type (Windows):: |
| 3025 |
|
| 3026 |
class _U(Union): |
| 3027 |
_fields_ = [("lptdesc", POINTER(TYPEDESC)), |
| 3028 |
("lpadesc", POINTER(ARRAYDESC)), |
| 3029 |
("hreftype", HREFTYPE)] |
| 3030 |
|
| 3031 |
class TYPEDESC(Structure): |
| 3032 |
_anonymous_ = ("u",) |
| 3033 |
_fields_ = [("u", _U), |
| 3034 |
("vt", VARTYPE)] |
| 3035 |
|
| 3036 |
|
| 3037 |
The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field |
| 3038 |
specifies which one of the union fields is valid. Since the ``u`` field |
| 3039 |
is defined as anonymous field, it is now possible to access the members |
| 3040 |
directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc`` |
| 3041 |
are equivalent, but the former is faster since it does not need to create |
| 3042 |
a temporary union instance:: |
| 3043 |
|
| 3044 |
td = TYPEDESC() |
| 3045 |
td.vt = VT_PTR |
| 3046 |
td.lptdesc = POINTER(some_type) |
| 3047 |
td.u.lptdesc = POINTER(some_type) |
| 3048 |
|
| 3049 |
It is possible to define sub-subclasses of structures, they inherit the |
| 3050 |
fields of the base class. If the subclass definition has a separate |
| 3051 |
:attr:`_fields_` variable, the fields specified in this are appended to the |
| 3052 |
fields of the base class. |
| 3053 |
|
| 3054 |
Structure and union constructors accept both positional and keyword |
| 3055 |
arguments. Positional arguments are used to initialize member fields in the |
| 3056 |
same order as they are appear in :attr:`_fields_`. Keyword arguments in the |
| 3057 |
constructor are interpreted as attribute assignments, so they will initialize |
| 3058 |
:attr:`_fields_` with the same name, or create new attributes for names not |
| 3059 |
present in :attr:`_fields_`. |
| 3060 |
|
| 3061 |
|
| 3062 |
.. class:: CField(*args, **kw) |
| 3063 |
|
| 3064 |
Descriptor for fields of a :class:`Structure` and :class:`Union`. |
| 3065 |
For example:: |
| 3066 |
|
| 3067 |
>>> class Color(Structure): |
| 3068 |
... _fields_ = ( |
| 3069 |
... ('red', c_uint8), |
| 3070 |
... ('green', c_uint8), |
| 3071 |
... ('blue', c_uint8), |
| 3072 |
... ('intense', c_bool, 1), |
| 3073 |
... ('blinking', c_bool, 1), |
| 3074 |
... ) |
| 3075 |
... |
| 3076 |
>>> Color.red |
| 3077 |
<ctypes.CField 'red' type=c_ubyte, ofs=0, size=1> |
| 3078 |
>>> Color.green.type |
| 3079 |
<class 'ctypes.c_ubyte'> |
| 3080 |
>>> Color.blue.byte_offset |
| 3081 |
2 |
| 3082 |
>>> Color.intense |
| 3083 |
<ctypes.CField 'intense' type=c_bool, ofs=3, bit_size=1, bit_offset=0> |
| 3084 |
>>> Color.blinking.bit_offset |
| 3085 |
1 |
| 3086 |
|
| 3087 |
All attributes are read-only. |
| 3088 |
|
| 3089 |
:class:`!CField` objects are created via :attr:`~Structure._fields_`; |
| 3090 |
do not instantiate the class directly. |
| 3091 |
|
| 3092 |
.. versionadded:: 3.14 |
| 3093 |
|
| 3094 |
Previously, descriptors only had ``offset`` and ``size`` attributes |
| 3095 |
and a readable string representation; the :class:`!CField` class was not |
| 3096 |
available directly. |
| 3097 |
|
| 3098 |
.. attribute:: name |
| 3099 |
|
| 3100 |
Name of the field, as a string. |
| 3101 |
|
| 3102 |
.. attribute:: type |
| 3103 |
|
| 3104 |
Type of the field, as a :ref:`ctypes class <ctypes-data-types>`. |
| 3105 |
|
| 3106 |
.. attribute:: offset |
| 3107 |
byte_offset |
| 3108 |
|
| 3109 |
Offset of the field, in bytes. |
| 3110 |
|
| 3111 |
For bitfields, this is the offset of the underlying byte-aligned |
| 3112 |
*storage unit*; see :attr:`~CField.bit_offset`. |
| 3113 |
|
| 3114 |
.. attribute:: byte_size |
| 3115 |
|
| 3116 |
Size of the field, in bytes. |
| 3117 |
|
| 3118 |
For bitfields, this is the size of the underlying *storage unit*. |
| 3119 |
Typically, it has the same size as the bitfield's type. |
| 3120 |
|
| 3121 |
.. attribute:: size |
| 3122 |
|
| 3123 |
For non-bitfields, equivalent to :attr:`~CField.byte_size`. |
| 3124 |
|
| 3125 |
For bitfields, this contains a backwards-compatible bit-packed |
| 3126 |
value that combines :attr:`~CField.bit_size` and |
| 3127 |
:attr:`~CField.bit_offset`. |
| 3128 |
Prefer using the explicit attributes instead. |
| 3129 |
|
| 3130 |
.. attribute:: is_bitfield |
| 3131 |
|
| 3132 |
True if this is a bitfield. |
| 3133 |
|
| 3134 |
.. attribute:: bit_offset |
| 3135 |
bit_size |
| 3136 |
|
| 3137 |
The location of a bitfield within its *storage unit*, that is, within |
| 3138 |
:attr:`~CField.byte_size` bytes of memory starting at |
| 3139 |
:attr:`~CField.byte_offset`. |
| 3140 |
|
| 3141 |
To get the field's value, read the storage unit as an integer, |
| 3142 |
:ref:`shift left <shifting>` by :attr:`!bit_offset` and |
| 3143 |
take the :attr:`!bit_size` least significant bits. |
| 3144 |
|
| 3145 |
For non-bitfields, :attr:`!bit_offset` is zero |
| 3146 |
and :attr:`!bit_size` is equal to ``byte_size * 8``. |
| 3147 |
|
| 3148 |
.. attribute:: is_anonymous |
| 3149 |
|
| 3150 |
True if this field is anonymous, that is, it contains nested sub-fields |
| 3151 |
that should be merged into a containing structure or union. |
| 3152 |
|
| 3153 |
|
| 3154 |
.. _ctypes-arrays-pointers: |
| 3155 |
|
| 3156 |
Arrays and pointers |
| 3157 |
^^^^^^^^^^^^^^^^^^^ |
| 3158 |
|
| 3159 |
.. class:: Array(*args) |
| 3160 |
|
| 3161 |
Abstract base class for arrays. |
| 3162 |
|
| 3163 |
The recommended way to create concrete array types is by multiplying any |
| 3164 |
:mod:`!ctypes` data type with a non-negative integer. Alternatively, you can subclass |
| 3165 |
this type and define :attr:`_length_` and :attr:`_type_` class variables. |
| 3166 |
Array elements can be read and written using standard |
| 3167 |
subscript and slice accesses; for slice reads, the resulting object is |
| 3168 |
*not* itself an :class:`Array`. |
| 3169 |
|
| 3170 |
Arrays are :ref:`generic <generics>` over the type of their elements. |
| 3171 |
|
| 3172 |
|
| 3173 |
.. attribute:: _length_ |
| 3174 |
|
| 3175 |
A positive integer specifying the number of elements in the array. |
| 3176 |
Out-of-range subscripts result in an :exc:`IndexError`. Will be |
| 3177 |
returned by :func:`len`. |
| 3178 |
|
| 3179 |
|
| 3180 |
.. attribute:: _type_ |
| 3181 |
|
| 3182 |
Specifies the type of each element in the array. |
| 3183 |
|
| 3184 |
|
| 3185 |
Array subclass constructors accept positional arguments, used to |
| 3186 |
initialize the elements in order. |
| 3187 |
|
| 3188 |
.. function:: ARRAY(type, length) |
| 3189 |
|
| 3190 |
Create an array. |
| 3191 |
Equivalent to ``type * length``, where *type* is a |
| 3192 |
:mod:`!ctypes` data type and *length* an integer. |
| 3193 |
|
| 3194 |
This function is :term:`soft deprecated` in favor of multiplication. |
| 3195 |
There are no plans to remove it. |
| 3196 |
|
| 3197 |
|
| 3198 |
.. class:: _Pointer |
| 3199 |
|
| 3200 |
Private, abstract base class for pointers. |
| 3201 |
|
| 3202 |
Concrete pointer types are created by calling :func:`POINTER` with the |
| 3203 |
type that will be pointed to; this is done automatically by |
| 3204 |
:func:`pointer`. |
| 3205 |
|
| 3206 |
If a pointer points to an array, its elements can be read and |
| 3207 |
written using standard subscript and slice accesses. Pointer objects |
| 3208 |
have no size, so :func:`len` will raise :exc:`TypeError`. Negative |
| 3209 |
subscripts will read from the memory *before* the pointer (as in C), and |
| 3210 |
out-of-range subscripts will probably crash with an access violation (if |
| 3211 |
you're lucky). |
| 3212 |
|
| 3213 |
|
| 3214 |
.. attribute:: _type_ |
| 3215 |
|
| 3216 |
Specifies the type pointed to. |
| 3217 |
|
| 3218 |
.. attribute:: contents |
| 3219 |
|
| 3220 |
Returns the object to which to pointer points. Assigning to this |
| 3221 |
attribute changes the pointer to point to the assigned object. |
| 3222 |
|
| 3223 |
|
| 3224 |
.. _ctypes-exceptions: |
| 3225 |
|
| 3226 |
Exceptions |
| 3227 |
^^^^^^^^^^ |
| 3228 |
|
| 3229 |
.. exception:: ArgumentError |
| 3230 |
|
| 3231 |
This exception is raised when a foreign function call cannot convert one of the |
| 3232 |
passed arguments. |
| 3233 |
|
| 3234 |
|
| 3235 |
.. exception:: COMError(hresult, text, details) |
| 3236 |
|
| 3237 |
This exception is raised when a COM method call failed. |
| 3238 |
|
| 3239 |
.. attribute:: hresult |
| 3240 |
|
| 3241 |
The integer value representing the error code. |
| 3242 |
|
| 3243 |
.. attribute:: text |
| 3244 |
|
| 3245 |
The error message. |
| 3246 |
|
| 3247 |
.. attribute:: details |
| 3248 |
|
| 3249 |
The 5-tuple ``(descr, source, helpfile, helpcontext, progid)``. |
| 3250 |
|
| 3251 |
*descr* is the textual description. *source* is the language-dependent |
| 3252 |
``ProgID`` for the class or application that raised the error. *helpfile* |
| 3253 |
is the path of the help file. *helpcontext* is the help context |
| 3254 |
identifier. *progid* is the ``ProgID`` of the interface that defined the |
| 3255 |
error. |
| 3256 |
|
| 3257 |
.. availability:: Windows |
| 3258 |
|
| 3259 |
.. versionadded:: 3.14 |