Python 透過標準庫 `ctypes` 呼叫 C/C++ 動態連結庫 (DLL/.so),是系統整合、硬體控制、效能關鍵路徑優化的關鍵技術。本文詳細說明 DLL 載入方式、呼叫慣例 (`stdcall` vs `cdecl`)、指標/緩衝區處理、結構體對應與錯誤處理。
import ctypes
# Windows: 載入 stdcall 呼叫慣例 DLL (WinAPI 風格)
dll = ctypes.windll.LoadLibrary('test.dll')
# 等價於
dll = ctypes.WinDLL('test.dll')
# Windows/Linux: 載入 cdecl 呼叫慣例 DLL (C 標準庫風格)
dll = ctypes.cdll.LoadLibrary('test.dll') # Linux 通常為 .so
# 等價於
dll = ctypes.CDLL('test.dll')
關鍵差異:
C 定義:
// test.h
extern "C" {
// stdcall (Windows API 風格)
int __stdcall test_stdcall(void* p, int len);
// cdecl (標準 C 風格)
int __cdecl test_cdecl(void* p, int len);
}
sBuf = 'aaaaaaaaaabbbbbbbbbbbbbb'
# 建立 char* 指向字串緩衝區
pStr = ctypes.c_char_p()
pStr.value = sBuf.encode('utf-8') # bytes
# 轉為 void* (c_void_p)
pVoid = ctypes.cast(pStr, ctypes.c_void_p).value
# 呼叫 stdcall 版本
nRst = dll.test_stdcall(pVoid, len(pStr.value))
# 宣告函數簽名,ctypes 自動處理類型轉換
test = dll.test_cdecl
test.argtypes = [ctypes.c_char_p, ctypes.c_int] # 參數類型
test.restype = ctypes.c_int # 返回類型
# 直接傳 Python bytes/str,自動轉換
nRst = test(sBuf.encode('utf-8'), len(sBuf))
優點:類型檢查、自動編碼轉換、錯誤訊息清晰、程式碼可讀性高。
| C 類型 | ctypes 類型 | Python 類型 |
|---|---|---|
int | c_int | int |
long | c_long | int |
float | c_float | float |
double | c_double | float |
char | c_char | bytes (長度 1) |
char* | c_char_p | bytes / str (自動編碼) |
void* | c_void_p | int (記憶體位址) |
struct Foo* | POINTER(Foo) | Foo 實例 |
int[10] | c_int * 10 | 可疊代 (列表/元組) |
# C 定義
typedef struct {
int age;
float height;
char name[32];
} Student;
// Python 對應
class Student(ctypes.Structure):
_fields_ = [
('age', ctypes.c_int),
('height', ctypes.c_float),
('name', ctypes.c_char * 32), # 固定長度陣列
]
# 使用
stu = Student(25, 1.8, b'John')
dll.process_student(ctypes.byref(stu)) # 傳遞指標
print(stu.age, stu.height, stu.name.decode())
# C: typedef void (*callback_t)(int progress);
CALLBACK = ctypes.CFUNCTYPE(None, ctypes.c_int)
def py_callback(progress):
print(f"Progress: {progress}%")
c_callback = CALLBACK(py_callback)
dll.set_callback(c_callback)
# ⚠️ 必須保持 c_callback 存活 (全域變數或物件屬性),否則 GC 導致崩潰
import errno
# 設定錯誤檢查器
def errcheck(result, func, args):
if result == -1:
e = ctypes.get_errno()
raise OSError(e, os.strerror(e))
return result
dll.some_func.errcheck = errcheck
dll.some_func.restype = ctypes.c_int
import sys, ctypes
if sys.platform == 'win32':
lib = ctypes.WinDLL('mylib.dll')
else:
lib = ctypes.CDLL('libmylib.so')
# 統一介面
lib.my_func.argtypes = [...]
lib.my_func.restype = ...
Windows DLL 依賴搜尋順序:應用目錄 → 系統目錄 → PATH。若 DLL 有相依 DLL 不在搜尋路徑: