如何从一门外语线程(C ++)调用Python函数 [英] How to call a python function from a foreign language thread (C++)

查看:134
本文介绍了如何从一门外语线程(C ++)调用Python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发使用DirectShow来抓住从音频数据的程序
媒体文件。 DirectShow中使用线程的音频数据传递给回调
功能在我的计划,我让那个回调函数调用另一个
功能Python编写的。

I am developing a program that use DirectShow to grab audio data from media files. DirectShow use thread to pass audio data to the callback function in my program, and I let that callback function call another function in Python.

我用的Boost.Python为包装我的图书馆,回调函数:

I use Boost.Python to wrapper my library, the callback function :

class PythonCallback {
private:
    object m_Function;
public:
    PythonCallback(object obj)
        : m_Function(obj)
    {}

    void operator() (double time, const AudioData &data) {
        // Call the callback function in python
        m_Function(time, data);
    }

};

下面问题来了​​,DirectShow中的一个线程调用我的
PythonCallback,即调用在Python的功能。一旦来电,我
节目刚刚崩溃。我觉得这应该是线程问题。然后我
发现了这个文档:

Here comes the problem, a thread of DirectShow calls my PythonCallback, namely, call the function in Python. Once it calls, my program just crash. I found this should be threading problem. Then I found this document:

http://docs.python.org/c-api/init.html

看来,我的程序无法调用从线程Python的功能
直接,因为那里是全球国米preTER锁。蟒蛇的GIL
是如此复杂,我不知道它是如何工作的。对不起,我能做些什么
是问。我的问题是。我应该之前和之后我所说的做
从线程Python函数?

It seems that my program can't call to Python's function from thread directly, because there is Global Interpreter Lock. The python's GIL is so complex, I have no idea how it works. I'm sorry, what I can do is to ask. My question is. What should I do before and after I call a Python function from threads?

这可能看起来是这样的。

It may looks like this.

void operator() (double time, const AudioData &data) {
    // acquire lock
    m_Function(time, data);
    // release lock
}

感谢。
维克多林。

Thanks. Victor Lin.

推荐答案

看看PyGILState_Ensure()/ PyGILState_Release(),从PEP 311
http://www.python.org/dev/peps/pep-0311/

Take a look at PyGILState_Ensure()/PyGILState_Release(), from PEP 311 http://www.python.org/dev/peps/pep-0311/

下面是从PEP本身采取了一个例子:

Here is an example taken from the PEP itself:

void SomeCFunction(void)
{
    /* ensure we hold the lock */
    PyGILState_STATE state = PyGILState_Ensure();
    /* Use the Python API */
    ...
    /* Restore the state of Python */
    PyGILState_Release(state);
}

这篇关于如何从一门外语线程(C ++)调用Python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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