2011-01-14 341 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)