关于 Python Ctypes 调用 C callback function

2015-06-18 00:41:04 +08:00
 nooper
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 是一个实时运行的程序,不断的接受数据流。

2011 次点击
所在节点    Python
2 条回复
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
2015-06-18 01:18:08 +08:00
看走眼了。。。 只要保证callback对象不被GC,Threading应该没啥问题,因为Callback到Py代码时候调用了PyGILState_Ensure()

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/199401

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX