Python ctypes中的字段中的回调函数

时间:2011-01-14 14:05:46

标签: python callback field ctypes

我正在尝试使用ctypes在Python中为.dll库注册回调函数。但它需要结构/字段中的回调函数。因为它不起作用(没有错误但回调函数什么都不做)我想我错了。有人可以帮助我吗?

有一条代码可以解释我想要做的事情:

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)

2 个答案:

答案 0 :(得分:1)

您必须初始化tHandlerStructure

stHandlerStructure = tHandlerStructure(OnFirst,OnSecond)

您的代码中还有其他语法错误。最好剪切并粘贴代码,给出错误,并提供回溯。以下是:

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)

答案 1 :(得分:0)

如果这是您正在使用的完整代码,那么您已经定义并实例化了该结构,但实际上从未将回调放入其中。

stHandlerStructure = tHandlerStructure(OnFirst, OnSecond)