Python 程式設計/使用 ctypes 擴充套件
外觀
ctypes[1] 是 Python 的一個 外部函式介面 模組(包含在 Python 2.5 及更高版本中),它允許您載入動態庫並呼叫 C 函式。從技術上講,這並不算是擴充套件 Python,但它滿足了擴充套件 Python 的主要原因之一:與外部 C 程式碼進行互動。
庫使用 ctypes.CDLL 函式載入。載入庫後,庫內的函式可以直接作為常規的 Python 呼叫使用。例如,如果我們想放棄標準的 Python 列印語句,使用標準的 C 庫函式 printf,可以使用以下程式碼
from ctypes import *
libName = 'libc.so' # If you're on a UNIX-based system
libName = 'msvcrt.dll' # If you're on Windows
libc = CDLL(libName)
libc.printf("Hello, World!\n")
當然,您必須使用與您的作業系統匹配的 libName 行,並刪除其他行。如果一切順利,您應該在控制檯中看到著名的 Hello World 字串。
ctypes 預設情況下假定任何給定函式的返回型別為本機大小的有符號整數。有時您不希望函式返回任何內容,而有時您又希望函式返回其他型別。每個 ctypes 函式都有一個名為 restype 的屬性。當您將 ctypes 類分配給 restype 時,它會自動將函式的返回值轉換為該型別。
| ctypes 名稱 | C 型別 | Python 型別 | 註釋 |
|---|---|---|---|
| None | void | None | None 物件 |
| c_bool | C99 _Bool | bool | |
| c_byte | signed char | int | |
| c_char | signed char | str | 長度為 1 |
| c_char_p | char * | str | |
| c_double | double | float | |
| c_float | float | float | |
| c_int | signed int | int | |
| c_long | signed long | long | |
| c_longlong | signed long long | long | |
| c_short | signed short | long | |
| c_ubyte | unsigned char | int | |
| c_uint | unsigned int | int | |
| c_ulong | unsigned long | long | |
| c_ulonglong | unsigned long long | long | |
| c_ushort | unsigned short | int | |
| c_void_p | void * | int | |
| c_wchar | wchar_t | unicode | 長度為 1 |
| c_wchar_p | wchar_t * | unicode |