python Ctype : problem with callback in making python custom library
The whole scenario is like this:
- 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.")
- Now,anothe开发者_如何学JAVAr python program uses above function from my python library to do the work,but the problem is:
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.
is there any workaround/solution to this problem?or am i missing something? please suggest... thanx in advance
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.
精彩评论