开发者

Callback functions in field in Python ctypes

I am trying to register callback functions for .dll library in Python with ctypes. But it requires callback functions in structure/field. Because it doesn't work (no errors but callback functions are doing nothing) I suppose I am wrong. Could someone, please, help me?

The开发者_如何学编程re is a code hopefully explaining what I am trying to do:

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)


You have to initialize tHandlerStructure:

stHandlerStructure = tHandlerStructure(OnFirst,OnSecond)

There are other syntax errors in your code. It is best to cut-and-paste the code giving you an error, and provide the tracebacks as well. Below works:

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)


If this is the complete code you're using, then you've defined and instantiated the structure, but never actually put your callbacks in it.

stHandlerStructure = tHandlerStructure(OnFirst, OnSecond)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜