Skip to main content
 首页 » 编程设计

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

2025年05月04日8grandyang

我正在尝试使用 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) 

请您参考如下方法:

你必须初始化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)