2011-01-14 347 views
2

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

有一个代码,希望解释什么,我试图做的:

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) 

回答

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

太好了,谢谢你,现在它的作品。 – 2011-01-16 15:06:32

0

如果这是您正在使用的完整代码,那么你已经定义和实例化的结构,但从来没有真正把你的回调。

stHandlerStructure = tHandlerStructure(OnFirst, OnSecond)