python Ctype:回调在python自定义库中的问题 [英] python Ctype : problem with callback in making python custom library
问题描述
整个场景是这样的:
- 在我的c库中有一个函数setmessagelistener(a_structure,function_pointer) >
-
我在写一个 python库,这是一个包装器上面提到的c库使用 Ctypes 。
所以我做的是这样的:
- there is a function setmessagelistener(a_structure,function_pointer) in my c library.
i am writing a python library which is a wrapper on above mentioned c library using Ctypes. so what i did is something like this:
def setlistener(a_structure,function_pointer)
listenerDeclaration = CFUNCTYPE(c_void_p, c_void_p)
listenerFunction = listenerDeclaration(function_pointer)
setMsgListener = c_lib.setMessageListener
setMsgListener.argtypes = [c_void_p, c_void_p]
setMsgListener.restype = c_ubyte
if (setMsgListener(a_structure, listenerFunction)==0):
sys.exit("Error setting message listener.")
当我运行程序它给我分段错误,因为本地对象已经垃圾收集(我认为这样)当控制从库函数setListener()返回时,它是一个局部对象。
when i run the program it gives me segmentation fault because the local object( listenerfunction) is already garbage collected(i think so) when control returned from the library function setListener() as it being a local object.
有没有解决方案/解决方案?或者我失去了什么?
请提前...
beforex
is there any workaround/solution to this problem?or am i missing something? please suggest... thanx in advance
推荐答案
引用listenerFunction,只要它需要。
As you suspect, you need to keep a reference to listenerFunction as long as it is needed. Perhaps wrap the function in a class, create an instance and set the listenerFunction as a member variable.
See the Python documentation for ctypes callbacks, especially the important note at the end of the section.
这篇关于python Ctype:回调在python自定义库中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!