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.