PageRenderTime 59ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/Doc/library/ctypes.rst

http://unladen-swallow.googlecode.com/
ReStructuredText | 2482 lines | 1769 code | 713 blank | 0 comment | 0 complexity | 6bd179d674b269a799687de33ef31e0a MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. :mod:`ctypes` --- A foreign function library for Python.
  2. ========================================================
  3. .. module:: ctypes
  4. :synopsis: A foreign function library for Python.
  5. .. moduleauthor:: Thomas Heller <theller@python.net>
  6. .. versionadded:: 2.5
  7. ``ctypes`` is a foreign function library for Python. It provides C compatible
  8. data types, and allows calling functions in DLLs or shared libraries. It can be
  9. used to wrap these libraries in pure Python.
  10. .. _ctypes-ctypes-tutorial:
  11. ctypes tutorial
  12. ---------------
  13. Note: The code samples in this tutorial use ``doctest`` to make sure that they
  14. actually work. Since some code samples behave differently under Linux, Windows,
  15. or Mac OS X, they contain doctest directives in comments.
  16. Note: Some code samples reference the ctypes :class:`c_int` type. This type is
  17. an alias for the :class:`c_long` type on 32-bit systems. So, you should not be
  18. confused if :class:`c_long` is printed if you would expect :class:`c_int` ---
  19. they are actually the same type.
  20. .. _ctypes-loading-dynamic-link-libraries:
  21. Loading dynamic link libraries
  22. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  23. ``ctypes`` exports the *cdll*, and on Windows *windll* and *oledll*
  24. objects, for loading dynamic link libraries.
  25. You load libraries by accessing them as attributes of these objects. *cdll*
  26. loads libraries which export functions using the standard ``cdecl`` calling
  27. convention, while *windll* libraries call functions using the ``stdcall``
  28. calling convention. *oledll* also uses the ``stdcall`` calling convention, and
  29. assumes the functions return a Windows :class:`HRESULT` error code. The error
  30. code is used to automatically raise a :class:`WindowsError` exception when
  31. the function call fails.
  32. Here are some examples for Windows. Note that ``msvcrt`` is the MS standard C
  33. library containing most standard C functions, and uses the cdecl calling
  34. convention::
  35. >>> from ctypes import *
  36. >>> print windll.kernel32 # doctest: +WINDOWS
  37. <WinDLL 'kernel32', handle ... at ...>
  38. >>> print cdll.msvcrt # doctest: +WINDOWS
  39. <CDLL 'msvcrt', handle ... at ...>
  40. >>> libc = cdll.msvcrt # doctest: +WINDOWS
  41. >>>
  42. Windows appends the usual ``.dll`` file suffix automatically.
  43. On Linux, it is required to specify the filename *including* the extension to
  44. load a library, so attribute access can not be used to load libraries. Either the
  45. :meth:`LoadLibrary` method of the dll loaders should be used, or you should load
  46. the library by creating an instance of CDLL by calling the constructor::
  47. >>> cdll.LoadLibrary("libc.so.6") # doctest: +LINUX
  48. <CDLL 'libc.so.6', handle ... at ...>
  49. >>> libc = CDLL("libc.so.6") # doctest: +LINUX
  50. >>> libc # doctest: +LINUX
  51. <CDLL 'libc.so.6', handle ... at ...>
  52. >>>
  53. .. XXX Add section for Mac OS X.
  54. .. _ctypes-accessing-functions-from-loaded-dlls:
  55. Accessing functions from loaded dlls
  56. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  57. Functions are accessed as attributes of dll objects::
  58. >>> from ctypes import *
  59. >>> libc.printf
  60. <_FuncPtr object at 0x...>
  61. >>> print windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
  62. <_FuncPtr object at 0x...>
  63. >>> print windll.kernel32.MyOwnFunction # doctest: +WINDOWS
  64. Traceback (most recent call last):
  65. File "<stdin>", line 1, in ?
  66. File "ctypes.py", line 239, in __getattr__
  67. func = _StdcallFuncPtr(name, self)
  68. AttributeError: function 'MyOwnFunction' not found
  69. >>>
  70. Note that win32 system dlls like ``kernel32`` and ``user32`` often export ANSI
  71. as well as UNICODE versions of a function. The UNICODE version is exported with
  72. an ``W`` appended to the name, while the ANSI version is exported with an ``A``
  73. appended to the name. The win32 ``GetModuleHandle`` function, which returns a
  74. *module handle* for a given module name, has the following C prototype, and a
  75. macro is used to expose one of them as ``GetModuleHandle`` depending on whether
  76. UNICODE is defined or not::
  77. /* ANSI version */
  78. HMODULE GetModuleHandleA(LPCSTR lpModuleName);
  79. /* UNICODE version */
  80. HMODULE GetModuleHandleW(LPCWSTR lpModuleName);
  81. *windll* does not try to select one of them by magic, you must access the
  82. version you need by specifying ``GetModuleHandleA`` or ``GetModuleHandleW``
  83. explicitly, and then call it with strings or unicode strings
  84. respectively.
  85. Sometimes, dlls export functions with names which aren't valid Python
  86. identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use ``getattr``
  87. to retrieve the function::
  88. >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z") # doctest: +WINDOWS
  89. <_FuncPtr object at 0x...>
  90. >>>
  91. On Windows, some dlls export functions not by name but by ordinal. These
  92. functions can be accessed by indexing the dll object with the ordinal number::
  93. >>> cdll.kernel32[1] # doctest: +WINDOWS
  94. <_FuncPtr object at 0x...>
  95. >>> cdll.kernel32[0] # doctest: +WINDOWS
  96. Traceback (most recent call last):
  97. File "<stdin>", line 1, in ?
  98. File "ctypes.py", line 310, in __getitem__
  99. func = _StdcallFuncPtr(name, self)
  100. AttributeError: function ordinal 0 not found
  101. >>>
  102. .. _ctypes-calling-functions:
  103. Calling functions
  104. ^^^^^^^^^^^^^^^^^
  105. You can call these functions like any other Python callable. This example uses
  106. the ``time()`` function, which returns system time in seconds since the Unix
  107. epoch, and the ``GetModuleHandleA()`` function, which returns a win32 module
  108. handle.
  109. This example calls both functions with a NULL pointer (``None`` should be used
  110. as the NULL pointer)::
  111. >>> print libc.time(None) # doctest: +SKIP
  112. 1150640792
  113. >>> print hex(windll.kernel32.GetModuleHandleA(None)) # doctest: +WINDOWS
  114. 0x1d000000
  115. >>>
  116. ``ctypes`` tries to protect you from calling functions with the wrong number of
  117. arguments or the wrong calling convention. Unfortunately this only works on
  118. Windows. It does this by examining the stack after the function returns, so
  119. although an error is raised the function *has* been called::
  120. >>> windll.kernel32.GetModuleHandleA() # doctest: +WINDOWS
  121. Traceback (most recent call last):
  122. File "<stdin>", line 1, in ?
  123. ValueError: Procedure probably called with not enough arguments (4 bytes missing)
  124. >>> windll.kernel32.GetModuleHandleA(0, 0) # doctest: +WINDOWS
  125. Traceback (most recent call last):
  126. File "<stdin>", line 1, in ?
  127. ValueError: Procedure probably called with too many arguments (4 bytes in excess)
  128. >>>
  129. The same exception is raised when you call an ``stdcall`` function with the
  130. ``cdecl`` calling convention, or vice versa::
  131. >>> cdll.kernel32.GetModuleHandleA(None) # doctest: +WINDOWS
  132. Traceback (most recent call last):
  133. File "<stdin>", line 1, in ?
  134. ValueError: Procedure probably called with not enough arguments (4 bytes missing)
  135. >>>
  136. >>> windll.msvcrt.printf("spam") # doctest: +WINDOWS
  137. Traceback (most recent call last):
  138. File "<stdin>", line 1, in ?
  139. ValueError: Procedure probably called with too many arguments (4 bytes in excess)
  140. >>>
  141. To find out the correct calling convention you have to look into the C header
  142. file or the documentation for the function you want to call.
  143. On Windows, ``ctypes`` uses win32 structured exception handling to prevent
  144. crashes from general protection faults when functions are called with invalid
  145. argument values::
  146. >>> windll.kernel32.GetModuleHandleA(32) # doctest: +WINDOWS
  147. Traceback (most recent call last):
  148. File "<stdin>", line 1, in ?
  149. WindowsError: exception: access violation reading 0x00000020
  150. >>>
  151. There are, however, enough ways to crash Python with ``ctypes``, so you should
  152. be careful anyway.
  153. ``None``, integers, longs, byte strings and unicode strings are the only native
  154. Python objects that can directly be used as parameters in these function calls.
  155. ``None`` is passed as a C ``NULL`` pointer, byte strings and unicode strings are
  156. passed as pointer to the memory block that contains their data (``char *`` or
  157. ``wchar_t *``). Python integers and Python longs are passed as the platforms
  158. default C ``int`` type, their value is masked to fit into the C type.
  159. Before we move on calling functions with other parameter types, we have to learn
  160. more about ``ctypes`` data types.
  161. .. _ctypes-fundamental-data-types:
  162. Fundamental data types
  163. ^^^^^^^^^^^^^^^^^^^^^^
  164. ``ctypes`` defines a number of primitive C compatible data types :
  165. +----------------------+--------------------------------+----------------------------+
  166. | ctypes type | C type | Python type |
  167. +======================+================================+============================+
  168. | :class:`c_char` | ``char`` | 1-character string |
  169. +----------------------+--------------------------------+----------------------------+
  170. | :class:`c_wchar` | ``wchar_t`` | 1-character unicode string |
  171. +----------------------+--------------------------------+----------------------------+
  172. | :class:`c_byte` | ``char`` | int/long |
  173. +----------------------+--------------------------------+----------------------------+
  174. | :class:`c_ubyte` | ``unsigned char`` | int/long |
  175. +----------------------+--------------------------------+----------------------------+
  176. | :class:`c_short` | ``short`` | int/long |
  177. +----------------------+--------------------------------+----------------------------+
  178. | :class:`c_ushort` | ``unsigned short`` | int/long |
  179. +----------------------+--------------------------------+----------------------------+
  180. | :class:`c_int` | ``int`` | int/long |
  181. +----------------------+--------------------------------+----------------------------+
  182. | :class:`c_uint` | ``unsigned int`` | int/long |
  183. +----------------------+--------------------------------+----------------------------+
  184. | :class:`c_long` | ``long`` | int/long |
  185. +----------------------+--------------------------------+----------------------------+
  186. | :class:`c_ulong` | ``unsigned long`` | int/long |
  187. +----------------------+--------------------------------+----------------------------+
  188. | :class:`c_longlong` | ``__int64`` or ``long long`` | int/long |
  189. +----------------------+--------------------------------+----------------------------+
  190. | :class:`c_ulonglong` | ``unsigned __int64`` or | int/long |
  191. | | ``unsigned long long`` | |
  192. +----------------------+--------------------------------+----------------------------+
  193. | :class:`c_float` | ``float`` | float |
  194. +----------------------+--------------------------------+----------------------------+
  195. | :class:`c_double` | ``double`` | float |
  196. +----------------------+--------------------------------+----------------------------+
  197. | :class:`c_longdouble`| ``long double`` | float |
  198. +----------------------+--------------------------------+----------------------------+
  199. | :class:`c_char_p` | ``char *`` (NUL terminated) | string or ``None`` |
  200. +----------------------+--------------------------------+----------------------------+
  201. | :class:`c_wchar_p` | ``wchar_t *`` (NUL terminated) | unicode or ``None`` |
  202. +----------------------+--------------------------------+----------------------------+
  203. | :class:`c_void_p` | ``void *`` | int/long or ``None`` |
  204. +----------------------+--------------------------------+----------------------------+
  205. All these types can be created by calling them with an optional initializer of
  206. the correct type and value::
  207. >>> c_int()
  208. c_long(0)
  209. >>> c_char_p("Hello, World")
  210. c_char_p('Hello, World')
  211. >>> c_ushort(-3)
  212. c_ushort(65533)
  213. >>>
  214. Since these types are mutable, their value can also be changed afterwards::
  215. >>> i = c_int(42)
  216. >>> print i
  217. c_long(42)
  218. >>> print i.value
  219. 42
  220. >>> i.value = -99
  221. >>> print i.value
  222. -99
  223. >>>
  224. Assigning a new value to instances of the pointer types :class:`c_char_p`,
  225. :class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they
  226. point to, *not the contents* of the memory block (of course not, because Python
  227. strings are immutable)::
  228. >>> s = "Hello, World"
  229. >>> c_s = c_char_p(s)
  230. >>> print c_s
  231. c_char_p('Hello, World')
  232. >>> c_s.value = "Hi, there"
  233. >>> print c_s
  234. c_char_p('Hi, there')
  235. >>> print s # first string is unchanged
  236. Hello, World
  237. >>>
  238. You should be careful, however, not to pass them to functions expecting pointers
  239. to mutable memory. If you need mutable memory blocks, ctypes has a
  240. ``create_string_buffer`` function which creates these in various ways. The
  241. current memory block contents can be accessed (or changed) with the ``raw``
  242. property; if you want to access it as NUL terminated string, use the ``value``
  243. property::
  244. >>> from ctypes import *
  245. >>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes
  246. >>> print sizeof(p), repr(p.raw)
  247. 3 '\x00\x00\x00'
  248. >>> p = create_string_buffer("Hello") # create a buffer containing a NUL terminated string
  249. >>> print sizeof(p), repr(p.raw)
  250. 6 'Hello\x00'
  251. >>> print repr(p.value)
  252. 'Hello'
  253. >>> p = create_string_buffer("Hello", 10) # create a 10 byte buffer
  254. >>> print sizeof(p), repr(p.raw)
  255. 10 'Hello\x00\x00\x00\x00\x00'
  256. >>> p.value = "Hi"
  257. >>> print sizeof(p), repr(p.raw)
  258. 10 'Hi\x00lo\x00\x00\x00\x00\x00'
  259. >>>
  260. The ``create_string_buffer`` function replaces the ``c_buffer`` function (which
  261. is still available as an alias), as well as the ``c_string`` function from
  262. earlier ctypes releases. To create a mutable memory block containing unicode
  263. characters of the C type ``wchar_t`` use the ``create_unicode_buffer`` function.
  264. .. _ctypes-calling-functions-continued:
  265. Calling functions, continued
  266. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  267. Note that printf prints to the real standard output channel, *not* to
  268. ``sys.stdout``, so these examples will only work at the console prompt, not from
  269. within *IDLE* or *PythonWin*::
  270. >>> printf = libc.printf
  271. >>> printf("Hello, %s\n", "World!")
  272. Hello, World!
  273. 14
  274. >>> printf("Hello, %S\n", u"World!")
  275. Hello, World!
  276. 14
  277. >>> printf("%d bottles of beer\n", 42)
  278. 42 bottles of beer
  279. 19
  280. >>> printf("%f bottles of beer\n", 42.5)
  281. Traceback (most recent call last):
  282. File "<stdin>", line 1, in ?
  283. ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2
  284. >>>
  285. As has been mentioned before, all Python types except integers, strings, and
  286. unicode strings have to be wrapped in their corresponding ``ctypes`` type, so
  287. that they can be converted to the required C data type::
  288. >>> printf("An int %d, a double %f\n", 1234, c_double(3.14))
  289. An int 1234, a double 3.140000
  290. 31
  291. >>>
  292. .. _ctypes-calling-functions-with-own-custom-data-types:
  293. Calling functions with your own custom data types
  294. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  295. You can also customize ``ctypes`` argument conversion to allow instances of your
  296. own classes be used as function arguments. ``ctypes`` looks for an
  297. :attr:`_as_parameter_` attribute and uses this as the function argument. Of
  298. course, it must be one of integer, string, or unicode::
  299. >>> class Bottles(object):
  300. ... def __init__(self, number):
  301. ... self._as_parameter_ = number
  302. ...
  303. >>> bottles = Bottles(42)
  304. >>> printf("%d bottles of beer\n", bottles)
  305. 42 bottles of beer
  306. 19
  307. >>>
  308. If you don't want to store the instance's data in the :attr:`_as_parameter_`
  309. instance variable, you could define a ``property`` which makes the data
  310. available.
  311. .. _ctypes-specifying-required-argument-types:
  312. Specifying the required argument types (function prototypes)
  313. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  314. It is possible to specify the required argument types of functions exported from
  315. DLLs by setting the :attr:`argtypes` attribute.
  316. :attr:`argtypes` must be a sequence of C data types (the ``printf`` function is
  317. probably not a good example here, because it takes a variable number and
  318. different types of parameters depending on the format string, on the other hand
  319. this is quite handy to experiment with this feature)::
  320. >>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
  321. >>> printf("String '%s', Int %d, Double %f\n", "Hi", 10, 2.2)
  322. String 'Hi', Int 10, Double 2.200000
  323. 37
  324. >>>
  325. Specifying a format protects against incompatible argument types (just as a
  326. prototype for a C function), and tries to convert the arguments to valid types::
  327. >>> printf("%d %d %d", 1, 2, 3)
  328. Traceback (most recent call last):
  329. File "<stdin>", line 1, in ?
  330. ArgumentError: argument 2: exceptions.TypeError: wrong type
  331. >>> printf("%s %d %f\n", "X", 2, 3)
  332. X 2 3.000000
  333. 13
  334. >>>
  335. If you have defined your own classes which you pass to function calls, you have
  336. to implement a :meth:`from_param` class method for them to be able to use them
  337. in the :attr:`argtypes` sequence. The :meth:`from_param` class method receives
  338. the Python object passed to the function call, it should do a typecheck or
  339. whatever is needed to make sure this object is acceptable, and then return the
  340. object itself, its :attr:`_as_parameter_` attribute, or whatever you want to
  341. pass as the C function argument in this case. Again, the result should be an
  342. integer, string, unicode, a ``ctypes`` instance, or an object with an
  343. :attr:`_as_parameter_` attribute.
  344. .. _ctypes-return-types:
  345. Return types
  346. ^^^^^^^^^^^^
  347. By default functions are assumed to return the C ``int`` type. Other return
  348. types can be specified by setting the :attr:`restype` attribute of the function
  349. object.
  350. Here is a more advanced example, it uses the ``strchr`` function, which expects
  351. a string pointer and a char, and returns a pointer to a string::
  352. >>> strchr = libc.strchr
  353. >>> strchr("abcdef", ord("d")) # doctest: +SKIP
  354. 8059983
  355. >>> strchr.restype = c_char_p # c_char_p is a pointer to a string
  356. >>> strchr("abcdef", ord("d"))
  357. 'def'
  358. >>> print strchr("abcdef", ord("x"))
  359. None
  360. >>>
  361. If you want to avoid the ``ord("x")`` calls above, you can set the
  362. :attr:`argtypes` attribute, and the second argument will be converted from a
  363. single character Python string into a C char::
  364. >>> strchr.restype = c_char_p
  365. >>> strchr.argtypes = [c_char_p, c_char]
  366. >>> strchr("abcdef", "d")
  367. 'def'
  368. >>> strchr("abcdef", "def")
  369. Traceback (most recent call last):
  370. File "<stdin>", line 1, in ?
  371. ArgumentError: argument 2: exceptions.TypeError: one character string expected
  372. >>> print strchr("abcdef", "x")
  373. None
  374. >>> strchr("abcdef", "d")
  375. 'def'
  376. >>>
  377. You can also use a callable Python object (a function or a class for example) as
  378. the :attr:`restype` attribute, if the foreign function returns an integer. The
  379. callable will be called with the ``integer`` the C function returns, and the
  380. result of this call will be used as the result of your function call. This is
  381. useful to check for error return values and automatically raise an exception::
  382. >>> GetModuleHandle = windll.kernel32.GetModuleHandleA # doctest: +WINDOWS
  383. >>> def ValidHandle(value):
  384. ... if value == 0:
  385. ... raise WinError()
  386. ... return value
  387. ...
  388. >>>
  389. >>> GetModuleHandle.restype = ValidHandle # doctest: +WINDOWS
  390. >>> GetModuleHandle(None) # doctest: +WINDOWS
  391. 486539264
  392. >>> GetModuleHandle("something silly") # doctest: +WINDOWS
  393. Traceback (most recent call last):
  394. File "<stdin>", line 1, in ?
  395. File "<stdin>", line 3, in ValidHandle
  396. WindowsError: [Errno 126] The specified module could not be found.
  397. >>>
  398. ``WinError`` is a function which will call Windows ``FormatMessage()`` api to
  399. get the string representation of an error code, and *returns* an exception.
  400. ``WinError`` takes an optional error code parameter, if no one is used, it calls
  401. :func:`GetLastError` to retrieve it.
  402. Please note that a much more powerful error checking mechanism is available
  403. through the :attr:`errcheck` attribute; see the reference manual for details.
  404. .. _ctypes-passing-pointers:
  405. Passing pointers (or: passing parameters by reference)
  406. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  407. Sometimes a C api function expects a *pointer* to a data type as parameter,
  408. probably to write into the corresponding location, or if the data is too large
  409. to be passed by value. This is also known as *passing parameters by reference*.
  410. ``ctypes`` exports the :func:`byref` function which is used to pass parameters
  411. by reference. The same effect can be achieved with the ``pointer`` function,
  412. although ``pointer`` does a lot more work since it constructs a real pointer
  413. object, so it is faster to use :func:`byref` if you don't need the pointer
  414. object in Python itself::
  415. >>> i = c_int()
  416. >>> f = c_float()
  417. >>> s = create_string_buffer('\000' * 32)
  418. >>> print i.value, f.value, repr(s.value)
  419. 0 0.0 ''
  420. >>> libc.sscanf("1 3.14 Hello", "%d %f %s",
  421. ... byref(i), byref(f), s)
  422. 3
  423. >>> print i.value, f.value, repr(s.value)
  424. 1 3.1400001049 'Hello'
  425. >>>
  426. .. _ctypes-structures-unions:
  427. Structures and unions
  428. ^^^^^^^^^^^^^^^^^^^^^
  429. Structures and unions must derive from the :class:`Structure` and :class:`Union`
  430. base classes which are defined in the ``ctypes`` module. Each subclass must
  431. define a :attr:`_fields_` attribute. :attr:`_fields_` must be a list of
  432. *2-tuples*, containing a *field name* and a *field type*.
  433. The field type must be a ``ctypes`` type like :class:`c_int`, or any other
  434. derived ``ctypes`` type: structure, union, array, pointer.
  435. Here is a simple example of a POINT structure, which contains two integers named
  436. ``x`` and ``y``, and also shows how to initialize a structure in the
  437. constructor::
  438. >>> from ctypes import *
  439. >>> class POINT(Structure):
  440. ... _fields_ = [("x", c_int),
  441. ... ("y", c_int)]
  442. ...
  443. >>> point = POINT(10, 20)
  444. >>> print point.x, point.y
  445. 10 20
  446. >>> point = POINT(y=5)
  447. >>> print point.x, point.y
  448. 0 5
  449. >>> POINT(1, 2, 3)
  450. Traceback (most recent call last):
  451. File "<stdin>", line 1, in ?
  452. ValueError: too many initializers
  453. >>>
  454. You can, however, build much more complicated structures. Structures can itself
  455. contain other structures by using a structure as a field type.
  456. Here is a RECT structure which contains two POINTs named ``upperleft`` and
  457. ``lowerright`` ::
  458. >>> class RECT(Structure):
  459. ... _fields_ = [("upperleft", POINT),
  460. ... ("lowerright", POINT)]
  461. ...
  462. >>> rc = RECT(point)
  463. >>> print rc.upperleft.x, rc.upperleft.y
  464. 0 5
  465. >>> print rc.lowerright.x, rc.lowerright.y
  466. 0 0
  467. >>>
  468. Nested structures can also be initialized in the constructor in several ways::
  469. >>> r = RECT(POINT(1, 2), POINT(3, 4))
  470. >>> r = RECT((1, 2), (3, 4))
  471. Field :term:`descriptor`\s can be retrieved from the *class*, they are useful
  472. for debugging because they can provide useful information::
  473. >>> print POINT.x
  474. <Field type=c_long, ofs=0, size=4>
  475. >>> print POINT.y
  476. <Field type=c_long, ofs=4, size=4>
  477. >>>
  478. .. _ctypes-structureunion-alignment-byte-order:
  479. Structure/union alignment and byte order
  480. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  481. By default, Structure and Union fields are aligned in the same way the C
  482. compiler does it. It is possible to override this behavior be specifying a
  483. :attr:`_pack_` class attribute in the subclass definition. This must be set to a
  484. positive integer and specifies the maximum alignment for the fields. This is
  485. what ``#pragma pack(n)`` also does in MSVC.
  486. ``ctypes`` uses the native byte order for Structures and Unions. To build
  487. structures with non-native byte order, you can use one of the
  488. BigEndianStructure, LittleEndianStructure, BigEndianUnion, and LittleEndianUnion
  489. base classes. These classes cannot contain pointer fields.
  490. .. _ctypes-bit-fields-in-structures-unions:
  491. Bit fields in structures and unions
  492. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  493. It is possible to create structures and unions containing bit fields. Bit fields
  494. are only possible for integer fields, the bit width is specified as the third
  495. item in the :attr:`_fields_` tuples::
  496. >>> class Int(Structure):
  497. ... _fields_ = [("first_16", c_int, 16),
  498. ... ("second_16", c_int, 16)]
  499. ...
  500. >>> print Int.first_16
  501. <Field type=c_long, ofs=0:0, bits=16>
  502. >>> print Int.second_16
  503. <Field type=c_long, ofs=0:16, bits=16>
  504. >>>
  505. .. _ctypes-arrays:
  506. Arrays
  507. ^^^^^^
  508. Arrays are sequences, containing a fixed number of instances of the same type.
  509. The recommended way to create array types is by multiplying a data type with a
  510. positive integer::
  511. TenPointsArrayType = POINT * 10
  512. Here is an example of an somewhat artificial data type, a structure containing 4
  513. POINTs among other stuff::
  514. >>> from ctypes import *
  515. >>> class POINT(Structure):
  516. ... _fields_ = ("x", c_int), ("y", c_int)
  517. ...
  518. >>> class MyStruct(Structure):
  519. ... _fields_ = [("a", c_int),
  520. ... ("b", c_float),
  521. ... ("point_array", POINT * 4)]
  522. >>>
  523. >>> print len(MyStruct().point_array)
  524. 4
  525. >>>
  526. Instances are created in the usual way, by calling the class::
  527. arr = TenPointsArrayType()
  528. for pt in arr:
  529. print pt.x, pt.y
  530. The above code print a series of ``0 0`` lines, because the array contents is
  531. initialized to zeros.
  532. Initializers of the correct type can also be specified::
  533. >>> from ctypes import *
  534. >>> TenIntegers = c_int * 10
  535. >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
  536. >>> print ii
  537. <c_long_Array_10 object at 0x...>
  538. >>> for i in ii: print i,
  539. ...
  540. 1 2 3 4 5 6 7 8 9 10
  541. >>>
  542. .. _ctypes-pointers:
  543. Pointers
  544. ^^^^^^^^
  545. Pointer instances are created by calling the ``pointer`` function on a
  546. ``ctypes`` type::
  547. >>> from ctypes import *
  548. >>> i = c_int(42)
  549. >>> pi = pointer(i)
  550. >>>
  551. Pointer instances have a ``contents`` attribute which returns the object to
  552. which the pointer points, the ``i`` object above::
  553. >>> pi.contents
  554. c_long(42)
  555. >>>
  556. Note that ``ctypes`` does not have OOR (original object return), it constructs a
  557. new, equivalent object each time you retrieve an attribute::
  558. >>> pi.contents is i
  559. False
  560. >>> pi.contents is pi.contents
  561. False
  562. >>>
  563. Assigning another :class:`c_int` instance to the pointer's contents attribute
  564. would cause the pointer to point to the memory location where this is stored::
  565. >>> i = c_int(99)
  566. >>> pi.contents = i
  567. >>> pi.contents
  568. c_long(99)
  569. >>>
  570. .. XXX Document dereferencing pointers, and that it is preferred over the .contents attribute.
  571. Pointer instances can also be indexed with integers::
  572. >>> pi[0]
  573. 99
  574. >>>
  575. Assigning to an integer index changes the pointed to value::
  576. >>> print i
  577. c_long(99)
  578. >>> pi[0] = 22
  579. >>> print i
  580. c_long(22)
  581. >>>
  582. It is also possible to use indexes different from 0, but you must know what
  583. you're doing, just as in C: You can access or change arbitrary memory locations.
  584. Generally you only use this feature if you receive a pointer from a C function,
  585. and you *know* that the pointer actually points to an array instead of a single
  586. item.
  587. Behind the scenes, the ``pointer`` function does more than simply create pointer
  588. instances, it has to create pointer *types* first. This is done with the
  589. ``POINTER`` function, which accepts any ``ctypes`` type, and returns a new
  590. type::
  591. >>> PI = POINTER(c_int)
  592. >>> PI
  593. <class 'ctypes.LP_c_long'>
  594. >>> PI(42)
  595. Traceback (most recent call last):
  596. File "<stdin>", line 1, in ?
  597. TypeError: expected c_long instead of int
  598. >>> PI(c_int(42))
  599. <ctypes.LP_c_long object at 0x...>
  600. >>>
  601. Calling the pointer type without an argument creates a ``NULL`` pointer.
  602. ``NULL`` pointers have a ``False`` boolean value::
  603. >>> null_ptr = POINTER(c_int)()
  604. >>> print bool(null_ptr)
  605. False
  606. >>>
  607. ``ctypes`` checks for ``NULL`` when dereferencing pointers (but dereferencing
  608. invalid non-\ ``NULL`` pointers would crash Python)::
  609. >>> null_ptr[0]
  610. Traceback (most recent call last):
  611. ....
  612. ValueError: NULL pointer access
  613. >>>
  614. >>> null_ptr[0] = 1234
  615. Traceback (most recent call last):
  616. ....
  617. ValueError: NULL pointer access
  618. >>>
  619. .. _ctypes-type-conversions:
  620. Type conversions
  621. ^^^^^^^^^^^^^^^^
  622. Usually, ctypes does strict type checking. This means, if you have
  623. ``POINTER(c_int)`` in the :attr:`argtypes` list of a function or as the type of
  624. a member field in a structure definition, only instances of exactly the same
  625. type are accepted. There are some exceptions to this rule, where ctypes accepts
  626. other objects. For example, you can pass compatible array instances instead of
  627. pointer types. So, for ``POINTER(c_int)``, ctypes accepts an array of c_int::
  628. >>> class Bar(Structure):
  629. ... _fields_ = [("count", c_int), ("values", POINTER(c_int))]
  630. ...
  631. >>> bar = Bar()
  632. >>> bar.values = (c_int * 3)(1, 2, 3)
  633. >>> bar.count = 3
  634. >>> for i in range(bar.count):
  635. ... print bar.values[i]
  636. ...
  637. 1
  638. 2
  639. 3
  640. >>>
  641. To set a POINTER type field to ``NULL``, you can assign ``None``::
  642. >>> bar.values = None
  643. >>>
  644. .. XXX list other conversions...
  645. Sometimes you have instances of incompatible types. In C, you can cast one
  646. type into another type. ``ctypes`` provides a ``cast`` function which can be
  647. used in the same way. The ``Bar`` structure defined above accepts
  648. ``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field,
  649. but not instances of other types::
  650. >>> bar.values = (c_byte * 4)()
  651. Traceback (most recent call last):
  652. File "<stdin>", line 1, in ?
  653. TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
  654. >>>
  655. For these cases, the ``cast`` function is handy.
  656. The ``cast`` function can be used to cast a ctypes instance into a pointer to a
  657. different ctypes data type. ``cast`` takes two parameters, a ctypes object that
  658. is or can be converted to a pointer of some kind, and a ctypes pointer type. It
  659. returns an instance of the second argument, which references the same memory
  660. block as the first argument::
  661. >>> a = (c_byte * 4)()
  662. >>> cast(a, POINTER(c_int))
  663. <ctypes.LP_c_long object at ...>
  664. >>>
  665. So, ``cast`` can be used to assign to the ``values`` field of ``Bar`` the
  666. structure::
  667. >>> bar = Bar()
  668. >>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
  669. >>> print bar.values[0]
  670. 0
  671. >>>
  672. .. _ctypes-incomplete-types:
  673. Incomplete Types
  674. ^^^^^^^^^^^^^^^^
  675. *Incomplete Types* are structures, unions or arrays whose members are not yet
  676. specified. In C, they are specified by forward declarations, which are defined
  677. later::
  678. struct cell; /* forward declaration */
  679. struct {
  680. char *name;
  681. struct cell *next;
  682. } cell;
  683. The straightforward translation into ctypes code would be this, but it does not
  684. work::
  685. >>> class cell(Structure):
  686. ... _fields_ = [("name", c_char_p),
  687. ... ("next", POINTER(cell))]
  688. ...
  689. Traceback (most recent call last):
  690. File "<stdin>", line 1, in ?
  691. File "<stdin>", line 2, in cell
  692. NameError: name 'cell' is not defined
  693. >>>
  694. because the new ``class cell`` is not available in the class statement itself.
  695. In ``ctypes``, we can define the ``cell`` class and set the :attr:`_fields_`
  696. attribute later, after the class statement::
  697. >>> from ctypes import *
  698. >>> class cell(Structure):
  699. ... pass
  700. ...
  701. >>> cell._fields_ = [("name", c_char_p),
  702. ... ("next", POINTER(cell))]
  703. >>>
  704. Lets try it. We create two instances of ``cell``, and let them point to each
  705. other, and finally follow the pointer chain a few times::
  706. >>> c1 = cell()
  707. >>> c1.name = "foo"
  708. >>> c2 = cell()
  709. >>> c2.name = "bar"
  710. >>> c1.next = pointer(c2)
  711. >>> c2.next = pointer(c1)
  712. >>> p = c1
  713. >>> for i in range(8):
  714. ... print p.name,
  715. ... p = p.next[0]
  716. ...
  717. foo bar foo bar foo bar foo bar
  718. >>>
  719. .. _ctypes-callback-functions:
  720. Callback functions
  721. ^^^^^^^^^^^^^^^^^^
  722. ``ctypes`` allows to create C callable function pointers from Python callables.
  723. These are sometimes called *callback functions*.
  724. First, you must create a class for the callback function, the class knows the
  725. calling convention, the return type, and the number and types of arguments this
  726. function will receive.
  727. The CFUNCTYPE factory function creates types for callback functions using the
  728. normal cdecl calling convention, and, on Windows, the WINFUNCTYPE factory
  729. function creates types for callback functions using the stdcall calling
  730. convention.
  731. Both of these factory functions are called with the result type as first
  732. argument, and the callback functions expected argument types as the remaining
  733. arguments.
  734. I will present an example here which uses the standard C library's :func:`qsort`
  735. function, this is used to sort items with the help of a callback function.
  736. :func:`qsort` will be used to sort an array of integers::
  737. >>> IntArray5 = c_int * 5
  738. >>> ia = IntArray5(5, 1, 7, 33, 99)
  739. >>> qsort = libc.qsort
  740. >>> qsort.restype = None
  741. >>>
  742. :func:`qsort` must be called with a pointer to the data to sort, the number of
  743. items in the data array, the size of one item, and a pointer to the comparison
  744. function, the callback. The callback will then be called with two pointers to
  745. items, and it must return a negative integer if the first item is smaller than
  746. the second, a zero if they are equal, and a positive integer else.
  747. So our callback function receives pointers to integers, and must return an
  748. integer. First we create the ``type`` for the callback function::
  749. >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
  750. >>>
  751. For the first implementation of the callback function, we simply print the
  752. arguments we get, and return 0 (incremental development ;-)::
  753. >>> def py_cmp_func(a, b):
  754. ... print "py_cmp_func", a, b
  755. ... return 0
  756. ...
  757. >>>
  758. Create the C callable callback::
  759. >>> cmp_func = CMPFUNC(py_cmp_func)
  760. >>>
  761. And we're ready to go::
  762. >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
  763. py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
  764. py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
  765. py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
  766. py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
  767. py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
  768. py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
  769. py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
  770. py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
  771. py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
  772. py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
  773. >>>
  774. We know how to access the contents of a pointer, so lets redefine our callback::
  775. >>> def py_cmp_func(a, b):
  776. ... print "py_cmp_func", a[0], b[0]
  777. ... return 0
  778. ...
  779. >>> cmp_func = CMPFUNC(py_cmp_func)
  780. >>>
  781. Here is what we get on Windows::
  782. >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
  783. py_cmp_func 7 1
  784. py_cmp_func 33 1
  785. py_cmp_func 99 1
  786. py_cmp_func 5 1
  787. py_cmp_func 7 5
  788. py_cmp_func 33 5
  789. py_cmp_func 99 5
  790. py_cmp_func 7 99
  791. py_cmp_func 33 99
  792. py_cmp_func 7 33
  793. >>>
  794. It is funny to see that on linux the sort function seems to work much more
  795. efficient, it is doing less comparisons::
  796. >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +LINUX
  797. py_cmp_func 5 1
  798. py_cmp_func 33 99
  799. py_cmp_func 7 33
  800. py_cmp_func 5 7
  801. py_cmp_func 1 7
  802. >>>
  803. Ah, we're nearly done! The last step is to actually compare the two items and
  804. return a useful result::
  805. >>> def py_cmp_func(a, b):
  806. ... print "py_cmp_func", a[0], b[0]
  807. ... return a[0] - b[0]
  808. ...
  809. >>>
  810. Final run on Windows::
  811. >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +WINDOWS
  812. py_cmp_func 33 7
  813. py_cmp_func 99 33
  814. py_cmp_func 5 99
  815. py_cmp_func 1 99
  816. py_cmp_func 33 7
  817. py_cmp_func 1 33
  818. py_cmp_func 5 33
  819. py_cmp_func 5 7
  820. py_cmp_func 1 7
  821. py_cmp_func 5 1
  822. >>>
  823. and on Linux::
  824. >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX
  825. py_cmp_func 5 1
  826. py_cmp_func 33 99
  827. py_cmp_func 7 33
  828. py_cmp_func 1 7
  829. py_cmp_func 5 7
  830. >>>
  831. It is quite interesting to see that the Windows :func:`qsort` function needs
  832. more comparisons than the linux version!
  833. As we can easily check, our array is sorted now::
  834. >>> for i in ia: print i,
  835. ...
  836. 1 5 7 33 99
  837. >>>
  838. **Important note for callback functions:**
  839. Make sure you keep references to CFUNCTYPE objects as long as they are used from
  840. C code. ``ctypes`` doesn't, and if you don't, they may be garbage collected,
  841. crashing your program when a callback is made.
  842. .. _ctypes-accessing-values-exported-from-dlls:
  843. Accessing values exported from dlls
  844. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  845. Some shared libraries not only export functions, they also export variables. An
  846. example in the Python library itself is the ``Py_OptimizeFlag``, an integer set
  847. to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on
  848. startup.
  849. ``ctypes`` can access values like this with the :meth:`in_dll` class methods of
  850. the type. *pythonapi* is a predefined symbol giving access to the Python C
  851. api::
  852. >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
  853. >>> print opt_flag
  854. c_long(0)
  855. >>>
  856. If the interpreter would have been started with :option:`-O`, the sample would
  857. have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been
  858. specified.
  859. An extended example which also demonstrates the use of pointers accesses the
  860. ``PyImport_FrozenModules`` pointer exported by Python.
  861. Quoting the Python docs: *This pointer is initialized to point to an array of
  862. "struct _frozen" records, terminated by one whose members are all NULL or zero.
  863. When a frozen module is imported, it is searched in this table. Third-party code
  864. could play tricks with this to provide a dynamically created collection of
  865. frozen modules.*
  866. So manipulating this pointer could even prove useful. To restrict the example
  867. size, we show only how this table can be read with ``ctypes``::
  868. >>> from ctypes import *
  869. >>>
  870. >>> class struct_frozen(Structure):
  871. ... _fields_ = [("name", c_char_p),
  872. ... ("code", POINTER(c_ubyte)),
  873. ... ("size", c_int)]
  874. ...
  875. >>>
  876. We have defined the ``struct _frozen`` data type, so we can get the pointer to
  877. the table::
  878. >>> FrozenTable = POINTER(struct_frozen)
  879. >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
  880. >>>
  881. Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we
  882. can iterate over it, but we just have to make sure that our loop terminates,
  883. because pointers have no size. Sooner or later it would probably crash with an
  884. access violation or whatever, so it's better to break out of the loop when we
  885. hit the NULL entry::
  886. >>> for item in table:
  887. ... print item.name, item.size
  888. ... if item.name is None:
  889. ... break
  890. ...
  891. __hello__ 104
  892. __phello__ -104
  893. __phello__.spam 104
  894. None 0
  895. >>>
  896. The fact that standard Python has a frozen module and a frozen package
  897. (indicated by the negative size member) is not well known, it is only used for
  898. testing. Try it out with ``import __hello__`` for example.
  899. .. _ctypes-surprises:
  900. Surprises
  901. ^^^^^^^^^
  902. There are some edges in ``ctypes`` where you may be expect something else than
  903. what actually happens.
  904. Consider the following example::
  905. >>> from ctypes import *
  906. >>> class POINT(Structure):
  907. ... _fields_ = ("x", c_int), ("y", c_int)
  908. ...
  909. >>> class RECT(Structure):
  910. ... _fields_ = ("a", POINT), ("b", POINT)
  911. ...
  912. >>> p1 = POINT(1, 2)
  913. >>> p2 = POINT(3, 4)
  914. >>> rc = RECT(p1, p2)
  915. >>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
  916. 1 2 3 4
  917. >>> # now swap the two points
  918. >>> rc.a, rc.b = rc.b, rc.a
  919. >>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
  920. 3 4 3 4
  921. >>>
  922. Hm. We certainly expected the last statement to print ``3 4 1 2``. What
  923. happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
  924. >>> temp0, temp1 = rc.b, rc.a
  925. >>> rc.a = temp0
  926. >>> rc.b = temp1
  927. >>>
  928. Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of
  929. the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer
  930. contents of ``temp0`` into ``rc`` 's buffer. This, in turn, changes the
  931. contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have
  932. the expected effect.
  933. Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
  934. doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing
  935. the root-object's underlying buffer.
  936. Another example that may behave different from what one would expect is this::
  937. >>> s = c_char_p()
  938. >>> s.value = "abc def ghi"
  939. >>> s.value
  940. 'abc def ghi'
  941. >>> s.value is s.value
  942. False
  943. >>>
  944. Why is it printing ``False``? ctypes instances are objects containing a memory
  945. block plus some :term:`descriptor`\s accessing the contents of the memory.
  946. Storing a Python object in the memory block does not store the object itself,
  947. instead the ``contents`` of the object is stored. Accessing the contents again
  948. constructs a new Python object each time!
  949. .. _ctypes-variable-sized-data-types:
  950. Variable-sized data types
  951. ^^^^^^^^^^^^^^^^^^^^^^^^^
  952. ``ctypes`` provides some support for variable-sized arrays and structures (this
  953. was added in version 0.9.9.7).
  954. The ``resize`` function can be used to resize the memory buffer of an existing
  955. ctypes object. The function takes the object as first argument, and the
  956. requested size in bytes as the second argument. The memory block cannot be made
  957. smaller than the natural memory block specified by the objects type, a
  958. ``ValueError`` is raised if this is tried::
  959. >>> short_array = (c_short * 4)()
  960. >>> print sizeof(short_array)
  961. 8
  962. >>> resize(short_array, 4)
  963. Traceback (most recent call last):
  964. ...
  965. ValueError: minimum size is 8
  966. >>> resize(short_array, 32)
  967. >>> sizeof(short_array)
  968. 32
  969. >>> sizeof(type(short_array))
  970. 8
  971. >>>
  972. This is nice and fine, but how would one access the additional elements
  973. contained in this array? Since the type still only knows about 4 elements, we
  974. get errors accessing other elements::
  975. >>> short_array[:]
  976. [0, 0, 0, 0]
  977. >>> short_array[7]
  978. Traceback (most recent call last):
  979. ...
  980. IndexError: invalid index
  981. >>>
  982. Another way to use variable-sized data types with ``ctypes`` is to use the
  983. dynamic nature of Python, and (re-)define the data type after the required size
  984. is already known, on a case by case basis.
  985. .. _ctypes-ctypes-reference:
  986. ctypes reference
  987. ----------------
  988. .. _ctypes-finding-shared-libraries:
  989. Finding shared libraries
  990. ^^^^^^^^^^^^^^^^^^^^^^^^
  991. When programming in a compiled language, shared libraries are accessed when
  992. compiling/linking a program, and when the program is run.
  993. The purpose of the ``find_library`` function is to locate a library in a way
  994. similar to what the compiler does (on platforms with several versions of a
  995. shared library the most recent should be loaded), while the ctypes library
  996. loaders act like when a program is run, and call the runtime loader directly.
  997. The ``ctypes.util`` module provides a function which can help to determine the
  998. library to load.
  999. .. data:: find_library(name)
  1000. :module: ctypes.util
  1001. :noindex:
  1002. Try to find a library and return a pathname. *name* is the library name without
  1003. any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this
  1004. is the form used for the posix linker option :option:`-l`). If no library can
  1005. be found, returns ``None``.
  1006. The exact functionality is system dependent.
  1007. On Linux, ``find_library`` tries to run external programs (/sbin/ldconfig, gcc,
  1008. and objdump) to find the library file. It returns the filename of the library
  1009. file. Here are some examples::
  1010. >>> from ctypes.util import find_library
  1011. >>> find_library("m")
  1012. 'libm.so.6'
  1013. >>> find_library("c")
  1014. 'libc.so.6'
  1015. >>> find_library("bz2")
  1016. 'libbz2.so.1.0'
  1017. >>>
  1018. On OS X, ``find_library`` tries several predefined naming schemes and paths to
  1019. locate the library, and returns a full pathname if successful::
  1020. >>> from ctypes.util import find_library
  1021. >>> find_library("c")
  1022. '/usr/lib/libc.dylib'
  1023. >>> find_library("m")
  1024. '/usr/lib/libm.dylib'
  1025. >>> find_library("bz2")
  1026. '/usr/lib/libbz2.dylib'
  1027. >>> find_library("AGL")
  1028. '/System/Library/Frameworks/AGL.framework/AGL'
  1029. >>>
  1030. On Windows, ``find_library`` searches along the system search path, and returns
  1031. the full pathname, but since there is no predefined naming scheme a call like
  1032. ``find_library("c")`` will fail and return ``None``.
  1033. If wrapping a shared library with ``ctypes``, it *may* be better to determine
  1034. the shared library name at development type, and hardcode that into the wrapper
  1035. module instead of using ``find_library`` to locate the library at runtime.
  1036. .. _ctypes-loading-shared-libraries:
  1037. Loading shared libraries
  1038. ^^^^^^^^^^^^^^^^^^^^^^^^
  1039. There are several ways to loaded shared libraries into the Python process. One
  1040. way is to instantiate one of the following classes:
  1041. .. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
  1042. Instances of this class represent loaded shared libraries. Functions in these
  1043. libraries use the standard C calling convention, and are assumed to return
  1044. ``int``.
  1045. .. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
  1046. Windows only: Instances of this class represent loaded shared libraries,
  1047. functions in these libraries use the ``stdcall`` calling convention, and are
  1048. assumed to return the windows specific :class:`HRESULT` code. :class:`HRESULT`
  1049. values contain information specifying whether the function call failed or
  1050. succeeded, together with additional error code. If the return value signals a
  1051. failure, an :class:`WindowsError` is automatically raised.
  1052. .. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)
  1053. Windows only: Instances of this class represent loaded shared libraries,
  1054. functions in these libraries use the ``stdcall`` calling convention, and are
  1055. assumed to return ``int`` by default.
  1056. On Windows CE only the standard calling convention is used, for convenience the
  1057. :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this
  1058. platform.
  1059. The Python :term:`global interpreter lock` is released before calling any
  1060. function exported by these libraries, and reacquired afterwards.
  1061. .. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)
  1062. Instances of this class behave like :class:`CDLL` instances, except that the
  1063. Python GIL is *not* released during the function call, and after the function
  1064. execution the Python error flag is checked. If the error flag is set, a Python
  1065. exception is raised.
  1066. Thus, this is only useful to call Python C api functions directly.
  1067. All these classes can be instantiated by calling them with at least one
  1068. argument, the pathname of the shared library. If you have an existing handle to
  1069. an already loaded shared library, it can be passed as the ``handle`` named
  1070. parameter, otherwise the underlying platforms ``dlopen`` or :meth:`LoadLibrary`
  1071. function is used to load the library into the process, and to get a handle to
  1072. it.
  1073. The *mode* parameter can be used to specify how the library is loaded. For
  1074. details, consult the ``dlopen(3)`` manpage, on Windows, *mode* is ignored.
  1075. The *use_errno* parameter, when set to True, enables a ctypes mechanism that
  1076. allows to access the system :data:`errno` error number in a safe way.
  1077. :mod:`ctypes` maintains a thread-local copy of the systems :data:`errno`
  1078. variable; if you call foreign functions created with ``use_errno=True`` then the
  1079. :data:`errno` value before the function call is swapped with the ctypes private
  1080. copy, the same happens immediately after the function call.
  1081. The function :func:`ctypes.get_errno` returns the value of the ctypes private
  1082. copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy
  1083. to a new value and returns the former value.
  1084. The *use_last_error* parameter, when set to True, enables the same mechanism for
  1085. the Windows error code which is managed by the :func:`GetLastError` and
  1086. :func:`SetLastError` Windows API functions; :func:`ctypes.get_last_error` and
  1087. :func:`ctypes.set_last_error` are used to request and change the ctypes private
  1088. copy of the windows error code.
  1089. .. versionadded:: 2.6
  1090. The ``use_last_error`` and ``use_errno`` optional parameters
  1091. were added.
  1092. .. data:: RTLD_GLOBAL
  1093. :noindex:
  1094. Flag to use as *mode* parameter. On platforms where this flag is not available,
  1095. it is defined as the integer zero.
  1096. .. data:: RTLD_LOCAL
  1097. :noindex:
  1098. Flag to use as *mode* parameter. On platforms where this is not available, it
  1099. is the same as *RTLD_GLOBAL*.
  1100. .. data:: DEFAULT_MODE
  1101. :noindex:
  1102. The default mode which is used to load shared libraries. On OSX 10.3, this is
  1103. *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*.
  1104. Instances of these classes have no public methods, however :meth:`__getattr__`
  1105. and :meth:`__getitem__` have special behavior: functions exported by the shared
  1106. library can be accessed as attributes of by index. Please note that both
  1107. :meth:`__getattr__` and :meth:`__getitem__` cache their result, so calling them
  1108. repeatedly returns the same object each time.
  1109. The following public attributes are available, their name starts with an
  1110. underscore to not clash with exported function names:
  1111. .. attribute:: PyDLL._handle
  1112. The system handle used to access the library.
  1113. .. attribute:: PyDLL._name
  1114. The name of the library passed in the constructor.
  1115. Shared libraries can also be loaded by using one of the prefabricated objects,
  1116. which are instances of the :class:`LibraryLoader` class, either by calling the
  1117. :meth:`LoadLibrary` method, or by retrieving the library as attribute of the
  1118. loader instance.
  1119. .. class:: LibraryLoader(dlltype)
  1120. Class which loads shared libraries. ``dlltype`` should be one of the
  1121. :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types.
  1122. :meth:`__getattr__` has special behavior: It allows to load a shared library by
  1123. accessing it as attribute of a library loader instance. The result is cached,
  1124. so repeated attribute accesses return the same library each time.
  1125. .. method:: LoadLibrary(name)
  1126. Load a shared library into the process and return it. This method always
  1127. returns a new instance of the library.
  1128. These prefabricated library loaders are available:
  1129. .. data:: cdll
  1130. :noindex:
  1131. Creates :class:`CDLL` instances.
  1132. .. data:: windll
  1133. :noindex:
  1134. Windows only: Creates :class:`WinDLL` instances.
  1135. .. data:: oledll
  1136. :noindex:
  1137. Windows only: Creates :class:`OleDLL` instances.
  1138. .. data:: pydll
  1139. :noindex:
  1140. Creates :class:`PyDLL` instances.
  1141. For accessing the C Python api directly, a ready-to-use Python shared library
  1142. object is available:
  1143. .. data:: pythonapi
  1144. :noindex:
  1145. An instance of :class:`PyDLL` that exposes Python C api functions as attributes.
  1146. Note that all these functions are assumed to return C ``int``, which is of
  1147. course not always the truth, so you have to assign the correct :attr:`restype`
  1148. attribute to use these functions.
  1149. .. _ctypes-foreign-functions:
  1150. Foreign functions
  1151. ^^^^^^^^^^^^^^^^^
  1152. As explained in the previous section, foreign functions can be accessed as
  1153. attributes of loaded shared libraries. The function objects created in this way
  1154. by default accept any number of arguments, accept any ctypes data instances as
  1155. arguments, and return the default result type specified by the library loader.
  1156. They are instances of a private class:
  1157. .. class:: _FuncPtr
  1158. Base class for C callable foreign functions.
  1159. Instances of foreign functions are also C compatible data types; they
  1160. represent C function pointers.
  1161. This behavior can be customized by assigning to special attributes of the
  1162. foreign function object.
  1163. .. attribute:: restype
  1164. Assign a ctypes type to specify the result type of the foreign function.
  1165. Use ``None`` for ``void`` a function not returning anything.
  1166. It is possible to assign a callable Python object that is not a ctypes
  1167. type, in this case the function is assumed to return a C ``int``, and the
  1168. callable will be called with this integer, allowing to do further
  1169. processing or error checking. Using this is deprecated, for more flexible
  1170. post processing or error checking use a ctypes data type as
  1171. :attr:`restype` and assign a callable to the :attr:`errcheck` attribute.
  1172. .. attribute:: argtypes
  1173. Assign a tuple of ctypes types to specify the argument types that the
  1174. function accepts. Functions using the ``stdcall`` calling convention can
  1175. only be called with the same number of arguments as the length of this
  1176. tuple; functions using the C calling convention accept additional,
  1177. unspecified arguments as well.
  1178. When a foreign function is called, each actual argument is passed to the
  1179. :meth:`from_param` class method of the items in the :attr:`argtypes`
  1180. tuple, this method allows to adapt the actual argument to an object that
  1181. the foreign function accepts. For example, a :class:`c_char_p` item in
  1182. the :attr:`argtypes` tuple will convert a unicode string passed as
  1183. argument into an byte string using ctypes conversion rules.
  1184. New: It is now possible to put items in argtypes which are not ctypes
  1185. types, but each item must have a :meth:`from_param` method which returns a
  1186. value usable as argument (integer, string, ctypes instance). This allows
  1187. to define adapters that can adapt custom objects as function parameters.
  1188. .. attribute:: errcheck
  1189. Assign a Python function or another callable to this attribute. The
  1190. callable will be called with three or more arguments:
  1191. .. function:: callable(result, func, arguments)
  1192. :noindex:
  1193. ``result`` is what the foreign function returns, as specified
  1194. by the :attr:`restype` attribute.
  1195. ``func`` is the foreign function object itself, this allows
  1196. to reuse the same callable object to check or post process
  1197. the results of several functions.
  1198. ``arguments`` is a tuple containing the parameters originally
  1199. passed to the function call, this allows to specialize the
  1200. behavior on the arguments used.
  1201. The object that this function returns will be returned from the
  1202. foreign function call, but it can also check the result value
  1203. and raise an exception if the foreign function call failed.
  1204. .. exception:: ArgumentError()
  1205. This exception is raised when a foreign function call cannot convert one of the
  1206. passed arguments.
  1207. .. _ctypes-function-prototypes:
  1208. Function prototypes
  1209. ^^^^^^^^^^^^^^^^^^^
  1210. Foreign functions can also be created by instantiating function prototypes.
  1211. Function prototypes are similar to function prototypes in C; they describe a
  1212. function (return type, argument types, calling convention) without defining an
  1213. implementation. The factory functions must be called with the desired result
  1214. type and the argument types of the function.
  1215. .. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
  1216. The returned function prototype creates functions that use the standard C
  1217. calling convention. The function will release the GIL during the call. If
  1218. *use_errno* is set to True, the ctypes private copy of the system
  1219. :data:`errno` variable is exchanged with the real :data:`errno` value bafore
  1220. and after the call; *use_last_error* does the same for the Windows error
  1221. code.
  1222. .. versionchanged:: 2.6
  1223. The optional *use_errno* and *use_last_error* parameters were added.
  1224. .. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)
  1225. Windows only: The returned function prototype creates functions that use the
  1226. ``stdcall`` calling convention, except on Windows CE where
  1227. :func:`WINFUNCTYPE` is the same as :func:`CFUNCTYPE`. The function will
  1228. release the GIL during the call. *use_errno* and *use_last_error* have the
  1229. same meaning as above.
  1230. .. function:: PYFUNCTYPE(restype, *argtypes)
  1231. The returned function prototype creates functions that use the Python calling
  1232. convention. The function will *not* release the GIL during the call.
  1233. Function prototypes created by these factory functions can be instantiated in
  1234. different ways, depending on the type and number of the parameters in the call:
  1235. .. function:: prototype(address)
  1236. :noindex:
  1237. :module:
  1238. Returns a foreign function at the specified address which must be an integer.
  1239. .. function:: prototype(callable)
  1240. :noindex:
  1241. :module:
  1242. Create a C callable function (a callback function) from a Python ``callable``.
  1243. .. function:: prototype(func_spec[, paramflags])
  1244. :noindex:
  1245. :module:
  1246. Returns a foreign function exported by a shared library. ``func_spec`` must be a
  1247. 2-tuple ``(name_or_ordinal, library)``. The first item is the name of the
  1248. exported function as string, or the ordinal of the exported function as small
  1249. integer. The second item is the shared library instance.
  1250. .. function:: prototype(vtbl_index, name[, paramflags[, iid]])
  1251. :noindex:
  1252. :module:
  1253. Returns a foreign function that will call a COM method. ``vtbl_index`` is the
  1254. index into the virtual function table, a small non-negative integer. *name* is
  1255. name of the COM method. *iid* is an optional pointer to the interface identifier
  1256. which is used in extended error reporting.
  1257. COM methods use a special calling convention: They require a pointer to the COM
  1258. interface as first argument, in addition to those parameters that are specified
  1259. in the :attr:`argtypes` tuple.
  1260. The optional *paramflags* parameter creates foreign function wrappers with much
  1261. more functionality than the features described above.
  1262. *paramflags* must be a tuple of the same length as :attr:`argtypes`.
  1263. Each item in this tuple contains further information about a parameter, it must
  1264. be a tuple containing one, two, or three items.
  1265. The first item is an integer containing a combination of direction
  1266. flags for the parameter:
  1267. 1
  1268. Specifies an input parameter to the function.
  1269. 2
  1270. Output parameter. The foreign function fills in a value.
  1271. 4
  1272. Input parameter which defaults to the integer zero.
  1273. The optional second item is the parameter name as string. If this is specified,
  1274. the foreign function can be called with named parameters.
  1275. The optional third item is the default value for this parameter.
  1276. This example demonstrates how to wrap the Windows ``MessageBoxA`` function so
  1277. that it supports default parameters and named arguments. The C declaration from
  1278. the windows header file is this::
  1279. WINUSERAPI int WINAPI
  1280. MessageBoxA(
  1281. HWND hWnd ,
  1282. LPCSTR lpText,
  1283. LPCSTR lpCaption,
  1284. UINT uType);
  1285. Here is the wrapping with ``ctypes``::
  1286. >>> from ctypes import c_int, WINFUNCTYPE, windll
  1287. >>> from ctypes.wintypes import HWND, LPCSTR, UINT
  1288. >>> prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
  1289. >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
  1290. >>> MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)
  1291. >>>
  1292. The MessageBox foreign function can now be called in these ways::
  1293. >>> MessageBox()
  1294. >>> MessageBox(text="Spam, spam, spam")
  1295. >>> MessageBox(flags=2, text="foo bar")
  1296. >>>
  1297. A second example demonstrates output parameters. The win32 ``GetWindowRect``
  1298. function retrieves the dimensions of a specified window by copying them into
  1299. ``RECT`` structure that the caller has to supply. Here is the C declaration::
  1300. WINUSERAPI BOOL WINAPI
  1301. GetWindowRect(
  1302. HWND hWnd,
  1303. LPRECT lpRect);
  1304. Here is the wrapping with ``ctypes``::
  1305. >>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
  1306. >>> from ctypes.wintypes import BOOL, HWND, RECT
  1307. >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
  1308. >>> paramflags = (1, "hwnd"), (2, "lprect")
  1309. >>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
  1310. >>>
  1311. Functions with output parameters will automatically return the output parameter
  1312. value if there is a single one, or a tuple containing the output parameter
  1313. values when there are more than one, so the GetWindowRect function now returns a
  1314. RECT instance, when called.
  1315. Output parameters can be combined with the :attr:`errcheck` protocol to do
  1316. further output processing and error checking. The win32 ``GetWindowRect`` api
  1317. function returns a ``BOOL`` to signal success or failure, so this function could
  1318. do the error checking, and raises an exception when the api call failed::
  1319. >>> def errcheck(result, func, args):
  1320. ... if not result:
  1321. ... raise WinError()
  1322. ... return args
  1323. ...
  1324. >>> GetWindowRect.errcheck = errcheck
  1325. >>>
  1326. If the :attr:`errcheck` function returns the argument tuple it receives
  1327. unchanged, ``ctypes`` continues the normal processing it does on the output
  1328. parameters. If you want to return a tuple of window coordinates instead of a
  1329. ``RECT`` instance, you can retrieve the fields in the function and return them
  1330. instead, the normal processing will no longer take place::
  1331. >>> def errcheck(result, func, args):
  1332. ... if not result:
  1333. ... raise WinError()
  1334. ... rc = args[1]
  1335. ... return rc.left, rc.top, rc.bottom, rc.right
  1336. ...
  1337. >>> GetWindowRect.errcheck = errcheck
  1338. >>>
  1339. .. _ctypes-utility-functions:
  1340. Utility functions
  1341. ^^^^^^^^^^^^^^^^^
  1342. .. function:: addressof(obj)
  1343. Returns the address of the memory buffer as integer. ``obj`` must be an
  1344. instance of a ctypes type.
  1345. .. function:: alignment(obj_or_type)
  1346. Returns the alignment requirements of a ctypes type. ``obj_or_type`` must be a
  1347. ctypes type or instance.
  1348. .. function:: byref(obj[, offset])
  1349. Returns a light-weight pointer to ``obj``, which must be an
  1350. instance of a ctypes type. ``offset`` defaults to zero, and must be
  1351. an integer that will be added to the internal pointer value.
  1352. ``byref(obj, offset)`` corresponds to this C code::
  1353. (((char *)&obj) + offset)
  1354. The returned object can only be used as a foreign function call
  1355. parameter. It behaves similar to ``pointer(obj)``, but the
  1356. construction is a lot faster.
  1357. .. versionadded:: 2.6
  1358. The ``offset`` optional argument was added.
  1359. .. function:: cast(obj, type)
  1360. This function is similar to the cast operator in C. It returns a new instance of
  1361. ``type`` which points to the same memory block as ``obj``. ``type`` must be a
  1362. pointer type, and ``obj`` must be an object that can be interpreted as a
  1363. pointer.
  1364. .. function:: create_string_buffer(init_or_size[, size])
  1365. This function creates a mutable character buffer. The returned object is a
  1366. ctypes array of :class:`c_char`.
  1367. ``init_or_size`` must be an integer which specifies the size of the array, or a
  1368. string which will be used to initialize the array items.
  1369. If a string is specified as first argument, the buffer is made one item larger
  1370. than the length of the string so that the last element in the array is a NUL
  1371. termination character. An integer can be passed as second argument which allows
  1372. to specify the size of the array if the length of the string should not be used.
  1373. If the first parameter is a unicode string, it is converted into an 8-bit string
  1374. according to ctypes conversion rules.
  1375. .. function:: create_unicode_buffer(init_or_size[, size])
  1376. This function creates a mutable unicode character buffer. The returned object is
  1377. a ctypes array of :class:`c_wchar`.
  1378. ``init_or_size`` must be an integer which specifies the size of the array, or a
  1379. unicode string which will be used to initialize the array items.
  1380. If a unicode string is specified as first argument, the buffer is made one item
  1381. larger than the length of the string so that the last element in the array is a
  1382. NUL termination character. An integer can be passed as second argument which
  1383. allows to specify the size of the array if the length of the string should not
  1384. be used.
  1385. If the first parameter is a 8-bit string, it is converted into an unicode string
  1386. according to ctypes conversion rules.
  1387. .. function:: DllCanUnloadNow()
  1388. Windows only: This function is a hook which allows to implement in-process COM
  1389. servers with ctypes. It is called from the DllCanUnloadNow function that the
  1390. _ctypes extension dll exports.
  1391. .. function:: DllGetClassObject()
  1392. Windows only: This function is a hook which allows to implement in-process COM
  1393. servers with ctypes. It is called from the DllGetClassObject function that the
  1394. ``_ctypes`` extension dll exports.
  1395. .. function:: find_library(name)
  1396. :module: ctypes.util
  1397. Try to find a library and return a pathname. *name* is the library name
  1398. without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version
  1399. number (this is the form used for the posix linker option :option:`-l`). If
  1400. no library can be found, returns ``None``.
  1401. The exact functionality is system dependent.
  1402. .. versionchanged:: 2.6
  1403. Windows only: ``find_library("m")`` or
  1404. ``find_library("c")`` return the result of a call to
  1405. ``find_msvcrt()``.
  1406. .. function:: find_msvcrt()
  1407. :module: ctypes.util
  1408. Windows only: return the filename of the VC runtype library used
  1409. by Python, and by the extension modules. If the name of the
  1410. library cannot be determined, ``None`` is returned.
  1411. If you need to free memory, for example, allocated by an extension
  1412. module with a call to the ``free(void *)``, it is important that you
  1413. use the function in the same library that allocated the memory.
  1414. .. versionadded:: 2.6
  1415. .. function:: FormatError([code])
  1416. Windows only: Returns a textual description of the error code. If no error code
  1417. is specified, the last error code is used by calling the Windows api function
  1418. GetLastError.
  1419. .. function:: GetLastError()
  1420. Windows only: Returns the last error code set by Windows in the calling thread.
  1421. This function calls the Windows `GetLastError()` function directly,
  1422. it does not return the ctypes-private copy of the error code.
  1423. .. function:: get_errno()
  1424. Returns the current value of the ctypes-private copy of the system
  1425. :data:`errno` variable in the calling thread.
  1426. .. versionadded:: 2.6
  1427. .. function:: get_last_error()
  1428. Windows only: returns the current value of the ctypes-private copy of the system
  1429. :data:`LastError` variable in the calling thread.
  1430. .. versionadded:: 2.6
  1431. .. function:: memmove(dst, src, count)
  1432. Same as the standard C memmove library function: copies *count* bytes from
  1433. ``src`` to *dst*. *dst* and ``src`` must be integers or ctypes instances that
  1434. can be converted to pointers.
  1435. .. function:: memset(dst, c, count)
  1436. Same as the standard C memset library function: fills the memory block at
  1437. address *dst* with *count* bytes of value *c*. *dst* must be an integer
  1438. specifying an address, or a ctypes instance.
  1439. .. function:: POINTER(type)
  1440. This factory function creates and returns a new ctypes pointer type. Pointer
  1441. types are cached an reused internally, so calling this function repeatedly is
  1442. cheap. type must be a ctypes type.
  1443. .. function:: pointer(obj)
  1444. This function creates a new pointer instance, pointing to ``obj``. The returned
  1445. object is of the type POINTER(type(obj)).
  1446. Note: If you just want to pass a pointer to an object to a foreign function
  1447. call, you should use ``byref(obj)`` which is much faster.
  1448. .. function:: resize(obj, size)
  1449. This function resizes the internal memory buffer of obj, which must be an
  1450. instance of a ctypes type. It is not possible to make the buffer smaller than
  1451. the native size of the objects type, as given by sizeof(type(obj)), but it is
  1452. possible to enlarge the buffer.
  1453. .. function:: set_conversion_mode(encoding, errors)
  1454. This function sets the rules that ctypes objects use when converting between
  1455. 8-bit strings and unicode strings. encoding must be a string specifying an
  1456. encoding, like ``'utf-8'`` or ``'mbcs'``, errors must be a string specifying the
  1457. error handling on encoding/decoding errors. Examples of possible values are
  1458. ``"strict"``, ``"replace"``, or ``"ignore"``.
  1459. ``set_conversion_mode`` returns a 2-tuple containing the previous conversion
  1460. rules. On windows, the initial conversion rules are ``('mbcs', 'ignore')``, on
  1461. other systems ``('ascii', 'strict')``.
  1462. .. function:: set_errno(value)
  1463. Set the current value of the ctypes-private copy of the system :data:`errno`
  1464. variable in the calling thread to *value* and return the previous value.
  1465. .. versionadded:: 2.6
  1466. .. function:: set_last_error(value)
  1467. Windows only: set the current value of the ctypes-private copy of the system
  1468. :data:`LastError` variable in the calling thread to *value* and return the
  1469. previous value.
  1470. .. versionadded:: 2.6
  1471. .. function:: sizeof(obj_or_type)
  1472. Returns the size in bytes of a ctypes type or instance memory buffer. Does the
  1473. same as the C ``sizeof()`` function.
  1474. .. function:: string_at(address[, size])
  1475. This function returns the string starting at memory address address. If size
  1476. is specified, it is used as size, otherwise the string is assumed to be
  1477. zero-terminated.
  1478. .. function:: WinError(code=None, descr=None)
  1479. Windows only: this function is probably the worst-named thing in ctypes. It
  1480. creates an instance of WindowsError. If *code* is not specified,
  1481. ``GetLastError`` is called to determine the error code. If ``descr`` is not
  1482. specified, :func:`FormatError` is called to get a textual description of the
  1483. error.
  1484. .. function:: wstring_at(address)
  1485. This function returns the wide character string starting at memory address
  1486. ``address`` as unicode string. If ``size`` is specified, it is used as the
  1487. number of characters of the string, otherwise the string is assumed to be
  1488. zero-terminated.
  1489. .. _ctypes-data-types:
  1490. Data types
  1491. ^^^^^^^^^^
  1492. .. class:: _CData
  1493. This non-public class is the common base class of all ctypes data types. Among
  1494. other things, all ctypes type instances contain a memory block that hold C
  1495. compatible data; the address of the memory block is returned by the
  1496. ``addressof()`` helper function. Another instance variable is exposed as
  1497. :attr:`_objects`; this contains other Python objects that need to be kept alive
  1498. in case the memory block contains pointers.
  1499. Common methods of ctypes data types, these are all class methods (to be
  1500. exact, they are methods of the :term:`metaclass`):
  1501. .. method:: _CData.from_buffer(source[, offset])
  1502. This method returns a ctypes instance that shares the buffer of
  1503. the ``source`` object. The ``source`` object must support the
  1504. writeable buffer interface. The optional ``offset`` parameter
  1505. specifies an offset into the source buffer in bytes; the default
  1506. is zero. If the source buffer is not large enough a ValueError
  1507. is raised.
  1508. .. versionadded:: 2.6
  1509. .. method:: _CData.from_buffer_copy(source[, offset])
  1510. This method creates a ctypes instance, copying the buffer from
  1511. the source object buffer which must be readable. The optional
  1512. ``offset`` parameter specifies an offset into the source buffer
  1513. in bytes; the default is zero. If the source buffer is not
  1514. large enough a ValueError is raised.
  1515. .. versionadded:: 2.6
  1516. .. method:: from_address(address)
  1517. This method returns a ctypes type instance using the memory specified by
  1518. address which must be an integer.
  1519. .. method:: from_param(obj)
  1520. This method adapts *obj* to a ctypes type. It is called with the actual
  1521. object used in a foreign function call when the type is present in the
  1522. foreign function's :attr:`argtypes` tuple; it must return an object that
  1523. can be used as a function call parameter.
  1524. All ctypes data types have a default implementation of this classmethod
  1525. that normally returns ``obj`` if that is an instance of the type. Some
  1526. types accept other objects as well.
  1527. .. method:: in_dll(library, name)
  1528. This method returns a ctypes type instance exported by a shared
  1529. library. *name* is the name of the symbol that exports the data, *library*
  1530. is the loaded shared library.
  1531. Common instance variables of ctypes data types:
  1532. .. attribute:: _b_base_
  1533. Sometimes ctypes data instances do not own the memory block they contain,
  1534. instead they share part of the memory block of a base object. The
  1535. :attr:`_b_base_` read-only member is the root ctypes object that owns the
  1536. memory block.
  1537. .. attribute:: _b_needsfree_
  1538. This read-only variable is true when the ctypes data instance has
  1539. allocated the memory block itself, false otherwise.
  1540. .. attribute:: _objects
  1541. This member is either ``None`` or a dictionary containing Python objects
  1542. that need to be kept alive so that the memory block contents is kept
  1543. valid. This object is only exposed for debugging; never modify the
  1544. contents of this dictionary.
  1545. .. _ctypes-fundamental-data-types-2:
  1546. Fundamental data types
  1547. ^^^^^^^^^^^^^^^^^^^^^^
  1548. .. class:: _SimpleCData
  1549. This non-public class is the base class of all fundamental ctypes data types. It
  1550. is mentioned here because it contains the common attributes of the fundamental
  1551. ctypes data types. ``_SimpleCData`` is a subclass of ``_CData``, so it inherits
  1552. their methods and attributes.
  1553. .. versionchanged:: 2.6
  1554. ctypes data types that are not and do not contain pointers can
  1555. now be pickled.
  1556. Instances have a single attribute:
  1557. .. attribute:: value
  1558. This attribute contains the actual value of the instance. For integer and
  1559. pointer types, it is an integer, for character types, it is a single
  1560. character string, for character pointer types it is a Python string or
  1561. unicode string.
  1562. When the ``value`` attribute is retrieved from a ctypes instance, usually
  1563. a new object is returned each time. ``ctypes`` does *not* implement
  1564. original object return, always a new object is constructed. The same is
  1565. true for all other ctypes object instances.
  1566. Fundamental data types, when returned as foreign function call results, or, for
  1567. example, by retrieving structure field members or array items, are transparently
  1568. converted to native Python types. In other words, if a foreign function has a
  1569. :attr:`restype` of :class:`c_char_p`, you will always receive a Python string,
  1570. *not* a :class:`c_char_p` instance.
  1571. Subclasses of fundamental data types do *not* inherit this behavior. So, if a
  1572. foreign functions :attr:`restype` is a subclass of :class:`c_void_p`, you will
  1573. receive an instance of this subclass from the function call. Of course, you can
  1574. get the value of the pointer by accessing the ``value`` attribute.
  1575. These are the fundamental ctypes data types:
  1576. .. class:: c_byte
  1577. Represents the C signed char datatype, and interprets the value as small
  1578. integer. The constructor accepts an optional integer initializer; no overflow
  1579. checking is done.
  1580. .. class:: c_char
  1581. Represents the C char datatype, and interprets the value as a single character.
  1582. The constructor accepts an optional string initializer, the length of the string
  1583. must be exactly one character.
  1584. .. class:: c_char_p
  1585. Represents the C char \* datatype, which must be a pointer to a zero-terminated
  1586. string. The constructor accepts an integer address, or a string.
  1587. .. class:: c_double
  1588. Represents the C double datatype. The constructor accepts an optional float
  1589. initializer.
  1590. .. class:: c_longdouble
  1591. Represents the C long double datatype. The constructor accepts an
  1592. optional float initializer. On platforms where ``sizeof(long
  1593. double) == sizeof(double)`` it is an alias to :class:`c_double`.
  1594. .. versionadded:: 2.6
  1595. .. class:: c_float
  1596. Represents the C float datatype. The constructor accepts an optional float
  1597. initializer.
  1598. .. class:: c_int
  1599. Represents the C signed int datatype. The constructor accepts an optional
  1600. integer initializer; no overflow checking is done. On platforms where
  1601. ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`.
  1602. .. class:: c_int8
  1603. Represents the C 8-bit ``signed int`` datatype. Usually an alias for
  1604. :class:`c_byte`.
  1605. .. class:: c_int16
  1606. Represents the C 16-bit signed int datatype. Usually an alias for
  1607. :class:`c_short`.
  1608. .. class:: c_int32
  1609. Represents the C 32-bit signed int datatype. Usually an alias for
  1610. :class:`c_int`.
  1611. .. class:: c_int64
  1612. Represents the C 64-bit ``signed int`` datatype. Usually an alias for
  1613. :class:`c_longlong`.
  1614. .. class:: c_long
  1615. Represents the C ``signed long`` datatype. The constructor accepts an optional
  1616. integer initializer; no overflow checking is done.
  1617. .. class:: c_longlong
  1618. Represents the C ``signed long long`` datatype. The constructor accepts an
  1619. optional integer initializer; no overflow checking is done.
  1620. .. class:: c_short
  1621. Represents the C ``signed short`` datatype. The constructor accepts an optional
  1622. integer initializer; no overflow checking is done.
  1623. .. class:: c_size_t
  1624. Represents the C ``size_t`` datatype.
  1625. .. class:: c_ubyte
  1626. Represents the C ``unsigned char`` datatype, it interprets the value as small
  1627. integer. The constructor accepts an optional integer initializer; no overflow
  1628. checking is done.
  1629. .. class:: c_uint
  1630. Represents the C ``unsigned int`` datatype. The constructor accepts an optional
  1631. integer initializer; no overflow checking is done. On platforms where
  1632. ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`.
  1633. .. class:: c_uint8
  1634. Represents the C 8-bit unsigned int datatype. Usually an alias for
  1635. :class:`c_ubyte`.
  1636. .. class:: c_uint16
  1637. Represents the C 16-bit unsigned int datatype. Usually an alias for
  1638. :class:`c_ushort`.
  1639. .. class:: c_uint32
  1640. Represents the C 32-bit unsigned int datatype. Usually an alias for
  1641. :class:`c_uint`.
  1642. .. class:: c_uint64
  1643. Represents the C 64-bit unsigned int datatype. Usually an alias for
  1644. :class:`c_ulonglong`.
  1645. .. class:: c_ulong
  1646. Represents the C ``unsigned long`` datatype. The constructor accepts an optional
  1647. integer initializer; no overflow checking is done.
  1648. .. class:: c_ulonglong
  1649. Represents the C ``unsigned long long`` datatype. The constructor accepts an
  1650. optional integer initializer; no overflow checking is done.
  1651. .. class:: c_ushort
  1652. Represents the C ``unsigned short`` datatype. The constructor accepts an
  1653. optional integer initializer; no overflow checking is done.
  1654. .. class:: c_void_p
  1655. Represents the C ``void *`` type. The value is represented as integer. The
  1656. constructor accepts an optional integer initializer.
  1657. .. class:: c_wchar
  1658. Represents the C ``wchar_t`` datatype, and interprets the value as a single
  1659. character unicode string. The constructor accepts an optional string
  1660. initializer, the length of the string must be exactly one character.
  1661. .. class:: c_wchar_p
  1662. Represents the C ``wchar_t *`` datatype, which must be a pointer to a
  1663. zero-terminated wide character string. The constructor accepts an integer
  1664. address, or a string.
  1665. .. class:: c_bool
  1666. Represent the C ``bool`` datatype (more accurately, _Bool from C99). Its value
  1667. can be True or False, and the constructor accepts any object that has a truth
  1668. value.
  1669. .. versionadded:: 2.6
  1670. .. class:: HRESULT
  1671. Windows only: Represents a :class:`HRESULT` value, which contains success or
  1672. error information for a function or method call.
  1673. .. class:: py_object
  1674. Represents the C ``PyObject *`` datatype. Calling this without an argument
  1675. creates a ``NULL`` ``PyObject *`` pointer.
  1676. The ``ctypes.wintypes`` module provides quite some other Windows specific data
  1677. types, for example ``HWND``, ``WPARAM``, or ``DWORD``. Some useful structures
  1678. like ``MSG`` or ``RECT`` are also defined.
  1679. .. _ctypes-structured-data-types:
  1680. Structured data types
  1681. ^^^^^^^^^^^^^^^^^^^^^
  1682. .. class:: Union(*args, **kw)
  1683. Abstract base class for unions in native byte order.
  1684. .. class:: BigEndianStructure(*args, **kw)
  1685. Abstract base class for structures in *big endian* byte order.
  1686. .. class:: LittleEndianStructure(*args, **kw)
  1687. Abstract base class for structures in *little endian* byte order.
  1688. Structures with non-native byte order cannot contain pointer type fields, or any
  1689. other data types containing pointer type fields.
  1690. .. class:: Structure(*args, **kw)
  1691. Abstract base class for structures in *native* byte order.
  1692. Concrete structure and union types must be created by subclassing one of these
  1693. types, and at least define a :attr:`_fields_` class variable. ``ctypes`` will
  1694. create :term:`descriptor`\s which allow reading and writing the fields by direct
  1695. attribute accesses. These are the
  1696. .. attribute:: _fields_
  1697. A sequence defining the structure fields. The items must be 2-tuples or
  1698. 3-tuples. The first item is the name of the field, the second item
  1699. specifies the type of the field; it can be any ctypes data type.
  1700. For integer type fields like :class:`c_int`, a third optional item can be
  1701. given. It must be a small positive integer defining the bit width of the
  1702. field.
  1703. Field names must be unique within one structure or union. This is not
  1704. checked, only one field can be accessed when names are repeated.
  1705. It is possible to define the :attr:`_fields_` class variable *after* the
  1706. class statement that defines the Structure subclass, this allows to create
  1707. data types that directly or indirectly reference themselves::
  1708. class List(Structure):
  1709. pass
  1710. List._fields_ = [("pnext", POINTER(List)),
  1711. ...
  1712. ]
  1713. The :attr:`_fields_` class variable must, however, be defined before the
  1714. type is first used (an instance is created, ``sizeof()`` is called on it,
  1715. and so on). Later assignments to the :attr:`_fields_` class variable will
  1716. raise an AttributeError.
  1717. Structure and union subclass constructors accept both positional and named
  1718. arguments. Positional arguments are used to initialize the fields in the
  1719. same order as they appear in the :attr:`_fields_` definition, named
  1720. arguments are used to initialize the fields with the corresponding name.
  1721. It is possible to defined sub-subclasses of structure types, they inherit
  1722. the fields of the base class plus the :attr:`_fields_` defined in the
  1723. sub-subclass, if any.
  1724. .. attribute:: _pack_
  1725. An optional small integer that allows to override the alignment of
  1726. structure fields in the instance. :attr:`_pack_` must already be defined
  1727. when :attr:`_fields_` is assigned, otherwise it will have no effect.
  1728. .. attribute:: _anonymous_
  1729. An optional sequence that lists the names of unnamed (anonymous) fields.
  1730. ``_anonymous_`` must be already defined when :attr:`_fields_` is assigned,
  1731. otherwise it will have no effect.
  1732. The fields listed in this variable must be structure or union type fields.
  1733. ``ctypes`` will create descriptors in the structure type that allows to
  1734. access the nested fields directly, without the need to create the
  1735. structure or union field.
  1736. Here is an example type (Windows)::
  1737. class _U(Union):
  1738. _fields_ = [("lptdesc", POINTER(TYPEDESC)),
  1739. ("lpadesc", POINTER(ARRAYDESC)),
  1740. ("hreftype", HREFTYPE)]
  1741. class TYPEDESC(Structure):
  1742. _fields_ = [("u", _U),
  1743. ("vt", VARTYPE)]
  1744. _anonymous_ = ("u",)
  1745. The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field
  1746. specifies which one of the union fields is valid. Since the ``u`` field
  1747. is defined as anonymous field, it is now possible to access the members
  1748. directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc``
  1749. are equivalent, but the former is faster since it does not need to create
  1750. a temporary union instance::
  1751. td = TYPEDESC()
  1752. td.vt = VT_PTR
  1753. td.lptdesc = POINTER(some_type)
  1754. td.u.lptdesc = POINTER(some_type)
  1755. It is possible to defined sub-subclasses of structures, they inherit the fields
  1756. of the base class. If the subclass definition has a separate :attr:`_fields_`
  1757. variable, the fields specified in this are appended to the fields of the base
  1758. class.
  1759. Structure and union constructors accept both positional and keyword arguments.
  1760. Positional arguments are used to initialize member fields in the same order as
  1761. they are appear in :attr:`_fields_`. Keyword arguments in the constructor are
  1762. interpreted as attribute assignments, so they will initialize :attr:`_fields_`
  1763. with the same name, or create new attributes for names not present in
  1764. :attr:`_fields_`.
  1765. .. _ctypes-arrays-pointers:
  1766. Arrays and pointers
  1767. ^^^^^^^^^^^^^^^^^^^
  1768. Not yet written - please see the sections :ref:`ctypes-pointers` and
  1769. section :ref:`ctypes-arrays` in the tutorial.