Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Python 調用 C 模組(二):深入 ctypes

前面整理過用 C 擴展 Python 的傳統方法,接著來學 ctypes。關於 ctypes 的評價兩極:有人覺得好用方便,也有人認為把標頭檔的宣告重新實作一遍頗麻煩。實際如何,還得看使用情境。

cdll、windll 與 oledll

ctypes 會導出 cdll,在 Windows 平台下還會額外提供 windll 與 oledll。三者都能載入動態連結庫,差別在呼叫約定:

  • cdll:載入函式符合 cdecl 呼叫約定的庫。
  • windll:載入函式符合 stdcall 呼叫約定的庫。
  • oledll:同樣使用 stdcall,並假設函式回傳 Windows 的 HRESULT 錯誤碼(會對應到 Python 的 WindowsError 例外)。

載入動態連結庫

Windows 下

Windows 通常以 .dll 作為副檔名,處理起來比較簡單,直接用 cdll、windll 或 oledll 的屬性操作即可:

>>> from ctypes import *
>>> print windll.kernel32
<WinDLL 'kernel32', handle ... at ...>
>>> print cdll.msvcrt
<CDLL 'msvcrt', handle ... at ...>

Linux 下

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。

Copyright © Linux教程網 All Rights Reserved