首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python ctypes 呼叫 DLL 完整指南:stdcall/cdecl、參數傳遞與緩衝區處理

     編輯:更多程式設計知識

Python ctypes 模組提供 C 相容資料類型與 DLL 共享庫呼叫功能,支援 stdcall (Windows API) 與 cdecl (C 標準) 兩種呼叫慣例。

載入 DLL


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

呼叫慣例對照表

慣例模組屬性類別適用場景
stdcallctypes.windllWinDLLWindows API
cdeclctypes.cdllCDLLC 標準庫、Linux .so
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved