我正在尝试使用 ctypes 在 Python 中包装 C 库。函数调用需要一个回调函数,我使用编程手册实现了该函数。问题是我无法从该包装器中获取“True”返回值,而且我是回调函数的新手。
from ctypes import *
class USB2ish(object):
def __init__(self):
try:
usbio_dll = cdll.LoadLibrary("C:\\Users\\...\\usb2uis.dll")
except:
print("dll file not loaded, 'USB-TO-UIS driver was not present/installed'.")
def exception_handler(self, exception):
print("Exception occured:", exception)
def USBIO_OpenDevice(self):
try:
result = cdll.usb2uis.USBIO_OpenDevice()
print('USBIO device Successfully opened with number', result)
return result
except Exception as ex:
self.exception_handler(self, ex)
def USBIO_SetTrigNotify(self, dev_no, result):
""" The trigger event of USB2UIS device, pTrig_CallBack will be called.
"""
# Define the callback function type
USB_DLL_CALLBACK = CFUNCTYPE(c_bool, POINTER(Set_trigg))
cl_back = USB_DLL_CALLBACK(self.process)
set_trig = Set_trigg(dev_no, 170) # "0x00AA" = 170
print(set_trig)
def process(self, dev_no, result):
print(dev_no.contents.dev_index)
print(result.contents.type)
if __name__ == "__main__":
rs = USB2ish()
result = rs.USBIO_OpenDevice()
call_back = rs.USBIO_SetTrigNotify(0, result)
如何在ctypes中使用回调方法?
三个问题:
首先声明:
USB_DLL_CALLBACK = CFUNCTYPE(c_bool, POINTER(Set_trigg))
根据编程手册,回调的签名必须是
bool function(BYTE, DWORD)
。
其次,我没有看到你在DLL中调用
USBIO_SetTrigNotify
的位置。
第三,您将
dev_no
和 result
作为参数传递给方法 USBIO_SetTrigNotify
,但这些将是 USBIO 将传递给您的回调的参数。
将所有内容放在一起(未经测试,因为我没有 DLL):
from ctypes import wintypes
from ctypes import *
class USB2ish(object):
def __init__(self):
try:
usbio_dll = cdll.LoadLibrary("C:\\Users\\...\\usb2uis.dll")
except:
print("dll file not loaded, 'USB-TO-UIS driver was not present/installed'.")
def exception_handler(self, exception):
print("Exception occured:", exception)
def USBIO_OpenDevice(self):
try:
result = cdll.usb2uis.USBIO_OpenDevice()
print('USBIO device Successfully opened with number', result)
return result
except Exception as ex:
self.exception_handler(self, ex)
def USBIO_SetTrigNotify(self):
callback = CFUNCTYPE(c_bool, BYTE, DWORD)(self.process)
return cdll.usb2uis.USBIO_SetTrigNOtify(callback)
def process(self, i_dev_index, i_type):
print(f'{i_dev_index=}')
print(f'{i_type=}')
if __name__ == "__main__":
rs = USB2ish()
result = rs.USBIO_OpenDevice()
rs.USBIO_SetTrigNotify()