萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 呼叫 DLL 完整指南:ctypes 載入、呼叫慣例、指標處理與跨平台差異

Python 透過標準庫 `ctypes` 呼叫 C/C++ 動態連結庫 (DLL/.so),是系統整合、硬體控制、效能關鍵路徑優化的關鍵技術。本文詳細說明 DLL 載入方式、呼叫慣例 (`stdcall` vs `cdecl`)、指標/緩衝區處理、結構體對應與錯誤處理。

DLL 載入方式


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')

關鍵差異:

  • `WinDLL` / `windll`:函數採用 `stdcall` (參數由被呼叫者清理堆疊),Windows API 標準。
  • `CDLL` / `cdll`:函數採用 `cdecl` (參數由呼叫者清理堆疊),C/C++ 編譯器預設。
  • **不匹配會導致堆疊破壞、崩潰或靜默錯誤**。

C 函數簽名對應

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))

方法二:argtypes/restype 自動封送 (推薦)


# 宣告函數簽名,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))

優點:類型檢查、自動編碼轉換、錯誤訊息清晰、程式碼可讀性高。

常用 ctypes 類型對應表

C 類型ctypes 類型Python 類型
intc_intint
longc_longint
floatc_floatfloat
doublec_doublefloat
charc_charbytes (長度 1)
char*c_char_pbytes / str (自動編碼)
void*c_void_pint (記憶體位址)
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 導致崩潰

錯誤處理與 errno


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 = ...

進階:載入依賴 DLL

Windows DLL 依賴搜尋順序:應用目錄 → 系統目錄 → PATH。若 DLL 有相依 DLL 不在搜尋路徑:

  • 將依賴 DLL 放在同目錄
  • 使用 `os.add_dll_directory(path)` (Python 3.8+)
  • 嵌入資訊清單 (Manifest) 指定依賴路徑

最佳實踐

  • **永遠宣告 `argtypes` 和 `restype`** - 類型安全、自動轉換、除錯友善。
  • **字串傳遞用 `bytes`** (配合 `c_char_p`),明確編碼 (通常 UTF-8)。
  • **結構體用 `ctypes.Structure` 定義** `_fields_`,注意對齊 (`_pack_`)。
  • **回呼函數持有引用** 防 GC。
  • **錯誤檢查器 `errcheck`** 統一處理 C 錯誤碼轉 Python 異常。
  • 大量資料傳輸考慮 `numpy.ctypeslib` 或共享記憶體 (`mmap`/`shared_memory`)。
copyright © 萬盛學電腦網 all rights reserved