Python ctypes中的字段回调函数

2 投票
2 回答
1818 浏览
提问于 2025-04-16 09:57

我正在尝试在Python中使用ctypes为.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

如果这是你使用的完整代码,那么你已经定义并创建了这个结构,但实际上你从来没有把你的回调函数放进去。

stHandlerStructure = tHandlerStructure(OnFirst, OnSecond)
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)

撰写回答