python Ctype:回调在python自定义库中的问题 [英] python Ctype : problem with callback in making python custom library

查看:447
本文介绍了python Ctype:回调在python自定义库中的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

整个场景是这样的:


  • 在我的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.")


  • 现在,另一个python程序使用上面的函数从我的python库做工作,但问题是:

  • 当我运行程序它给我分段错误,因为本地对象已经垃圾收集(我认为这样)当控制从库函数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.

    请参阅Python文档ctypes

    See the Python documentation for ctypes callbacks, especially the important note at the end of the section.

    这篇关于python Ctype:回调在python自定义库中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆