Python ctypes 模組提供 C 相容資料類型與 DLL 共享庫呼叫功能,支援 stdcall (Windows API) 與 cdecl (C 標準) 兩種呼叫慣例。
import ctypes
# stdcall (Windows API)
dll = ctypes.windll.LoadLibrary('test.dll')
# 或
dll = ctypes.WinDLL('test.dll')
# cdecl (C 標準庫)
dll = ctypes.cdll.LoadLibrary('test.dll')
# 或
dll = ctypes.CDLL('test.dll')
nRst = dll.test()
print(nRst)
方法一:手動轉型
sBuf = 'aaaaaaaaaabbbbbbbbbbbbbb'
pStr = ctypes.c_char_p()
pStr.value = sBuf
pVoid = ctypes.cast(pStr, ctypes.c_void_p).value
nRst = dll.test(pVoid, len(pStr.value))
方法二:宣告 argtypes/restype(推薦)
test = dll.test
test.argtypes = [ctypes.c_char_p, ctypes.c_int]
test.restype = ctypes.c_int
nRst = test(sBuf, len(sBuf))
| 慣例 | 模組屬性 | 類別 | 適用場景 |
|---|---|---|---|
| stdcall | ctypes.windll | WinDLL | Windows API |
| cdecl | ctypes.cdll | CDLL | C 標準庫、Linux .so |