V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
nooper
V2EX  ›  Python

关于 Python Ctypes 调用 C callback function

  •  
  •   nooper · 2015-06-18 00:41:04 +08:00 · 2007 次点击
    这是一个创建于 3252 天前的主题,其中的信息可能已经有所发展或是发生改变。
    from ctypes import *
    _CMPFUNC = CFUNCTYPE(c_bool,c_char_p)
    
    
    
    def __callback_function(output):
        """
        :return:
        """
        print output
        return True
    
    
    callback = _CMPFUNC(__callback_function)
    
    c_api.callbackfunc(callback)
    

    请问这里我用multiprocessor 或者 Threading , 或者 yield 协程会影响c的接口的回调吗?
    那我应该如何设计简单的callback 返回,我用 消息队列还是其他的方式,还是通知什么的?callback 是一个实时运行的程序,不断的接受数据流。

    2 条回复    2015-06-18 01:18:08 +08:00
    GeekGao
        1
    GeekGao  
       2015-06-18 00:55:37 +08:00
    极大的概率会发生access violation的。。。

    Make sure you keep references to CFUNCTYPE() objects as long as they are used from C code. ctypes doesn’t, and if you don’t, they may be garbage collected, crashing your program when a callback is made.
    Also, note that if the callback function is called in a thread created outside of Python’s control (e.g. by the foreign code that calls the callback), ctypes creates a new dummy Python thread on every invocation. This behavior is correct for most purposes, but it means that values stored with threading.local will not survive across different callbacks, even when those calls are made from the same C thread.

    ref:https://docs.python.org/2/library/ctypes.html#callback-functions
    GeekGao
        2
    GeekGao  
       2015-06-18 01:18:08 +08:00
    看走眼了。。。 只要保证callback对象不被GC,Threading应该没啥问题,因为Callback到Py代码时候调用了PyGILState_Ensure()
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3888 人在线   最高记录 6547   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 04:20 · PVG 12:20 · LAX 21:20 · JFK 00:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.