ctypes --- 用於 Python 的外部函式庫¶
原始碼:Lib/ctypes
ctypes is a foreign function library for Python. It provides C compatible
data types, and allows calling functions in DLLs or shared libraries. It can be
used to wrap these libraries in pure Python.
This is an optional module. If it is missing from your copy of CPython, look for documentation from your distributor (that is, whoever provided Python to you). If you are the distributor, see 可選模組的需求.
ctypes 教學¶
Note: Some code samples reference the ctypes c_int type. On platforms
where sizeof(long) == sizeof(int) it is an alias to c_long.
So, you should not be confused if c_long is printed if you would expect
c_int --- they are actually the same type.
Loading dynamic link libraries¶
ctypes exports the cdll, and on Windows
windll and oledll
objects, for loading dynamic link libraries.
You load libraries by accessing them as attributes of these objects.
cdll loads libraries which export functions using the
standard cdecl calling convention, while windll
libraries call functions using the stdcall
calling convention.
oledll also uses the stdcall calling convention, and
assumes the functions return a Windows HRESULT error code. The error
code is used to automatically raise an OSError exception when the
function call fails.
在 3.3 版的變更: Windows errors used to raise WindowsError, which is now an alias
of OSError.
Here are some examples for Windows. Note that msvcrt is the MS standard C
library containing most standard C functions, and uses the cdecl calling
convention:
>>> from ctypes import *
>>> print(windll.kernel32)
<WinDLL 'kernel32', handle ... at ...>
>>> print(cdll.msvcrt)
<CDLL 'msvcrt', handle ... at ...>
>>> libc = cdll.msvcrt
>>>
Windows appends the usual .dll file suffix automatically.
備註
Accessing the standard C library through cdll.msvcrt will use an
outdated version of the library that may be incompatible with the one
being used by Python. Where possible, use native Python functionality,
or else import and use the msvcrt module.
Other systems require the filename including the extension to
load a library, so attribute access can not be used to load libraries. Either the
LoadLibrary() method of the dll loaders should be used,
or you should load the library by creating an instance of CDLL
by calling the constructor.
舉例來說,在 Linux 上:
>>> cdll.LoadLibrary("libc.so.6")
<CDLL 'libc.so.6', handle ... at ...>
>>> libc = CDLL("libc.so.6")
>>> libc
<CDLL 'libc.so.6', handle ... at ...>
>>>
在 macOS 上:
>>> cdll.LoadLibrary("libc.dylib")
<CDLL 'libc.dylib', handle ... at ...>
>>> libc = CDLL("libc.dylib")
>>> libc
<CDLL 'libc.dylib', handle ... at ...>
Accessing functions from loaded dlls¶
Functions are accessed as attributes of dll objects:
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "ctypes.py", line 239, in