[英]Callback functions in field in Python ctypes
I am trying to register callback functions for .dll
library in Python with ctypes. 我正在尝试使用ctypes在Python中注册.dll
库的回调函数。 But it requires callback functions in structure/field. 但是它需要结构/字段中的回调函数。 Because it doesn't work (no errors but callback functions are doing nothing) I suppose I am wrong. 因为它不起作用(没有错误,但回调函数什么也不做),我想我错了。 Could someone, please, help me? 有人可以帮我吗?
There is a code hopefully explaining what I am trying to do: 有一个代码有望解释我正在尝试做的事情:
import ctypes
firsttype = CFUNCTYPE(c_void_p, c_int)
secondtype = CFUNCTYPE(c_void_p, c_int)
@firsttype
def OnFirst(i):
print "OnFirst"
@secondtype
def OnSecond(i):
print "OnSecond"
class tHandlerStructure(Structure):
`_fields_` = [
("firstCallback",firsttype),
("secondCallback",secondtype)
]
stHandlerStructure = tHandlerStructure()
ctypes.cdll.myDll.Initialize.argtypes = [POINTER(tHandlerStructure)]
ctypes.cdll.myDll.Initialize.restype = c_void_p
ctypes.cdll.myDll.Initialize(stHandleStructure)
You have to initialize tHandlerStructure
: 您必须初始化tHandlerStructure
:
stHandlerStructure = tHandlerStructure(OnFirst,OnSecond)
There are other syntax errors in your code. 您的代码中还有其他语法错误。 It is best to cut-and-paste the code giving you an error, and provide the tracebacks as well. 最好剪切并粘贴会给您带来错误的代码,并提供回溯。 Below works: 下面的作品:
from ctypes import *
firsttype = CFUNCTYPE(c_void_p, c_int)
secondtype = CFUNCTYPE(c_void_p, c_int)
@firsttype
def OnFirst(i):
print "OnFirst"
@secondtype
def OnSecond(i):
print "OnSecond"
class tHandlerStructure(Structure):
_fields_ = [
("firstCallback",firsttype),
("secondCallback",secondtype)
]
stHandlerStructure = tHandlerStructure(OnFirst,OnSecond)
cdll.myDll.Initialize.argtypes = [POINTER(tHandlerStructure)]
cdll.myDll.Initialize.restype = c_void_p
cdll.myDll.Initialize(stHandlerStructure)
如果这是您正在使用的完整代码,那么您已经定义并实例化了该结构,但从未实际将回调放入其中。
stHandlerStructure = tHandlerStructure(OnFirst, OnSecond)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.