前面整理過用 C 擴展 Python 的傳統方法,接著來學 ctypes。關於 ctypes 的評價兩極:有人覺得好用方便,也有人認為把標頭檔的宣告重新實作一遍頗麻煩。實際如何,還得看使用情境。
ctypes 會導出 cdll,在 Windows 平台下還會額外提供 windll 與 oledll。三者都能載入動態連結庫,差別在呼叫約定:
Windows 通常以 .dll 作為副檔名,處理起來比較簡單,直接用 cdll、windll 或 oledll 的屬性操作即可:
>>> from ctypes import * >>> print windll.kernel32 <WinDLL 'kernel32', handle ... at ...> >>> print cdll.msvcrt <CDLL 'msvcrt', handle ... at ...>
Linux 需要指定含副檔名的完整檔名來載入,因此屬性存取方式失效,得改用 LoadLibrary 或直接建立 CDLL 實例:
>>> cdll.LoadLibrary("libc.so.6")
<CDLL 'libc.so.6', handle ... at ...>
>>> libc == CDLL("libc.so.6")
>>> libc
<CDLL 'libc.so.6', handle ... at ...>
>>> from ctypes.util import find_library
>>> find_library("m")
>>> printf = ctypes.CDLL(find_library("c")).printf
ctypes 提供 c_char、c_wchar、c_byte、c_int、c_double 等值型別(皆為可變),以及 c_char_p、c_wchar_p、c_void_p 等指標型別(需謹慎使用):
>>> s = "Hello, world" >>> c_s = c_char_p(s)
由於 Python 的 string 是不可變的,這樣賦值其實只是換了位址。若需要可寫入的緩衝區,就該改用 create_string_buffer 或 create_unicode_buffer。