简体   繁体   English

从C ++调用Python函数

[英]Calling Python functions from C++

I am trying to achieve call Python functions from C++. 我正在尝试从C ++实现调用Python函数。 I thought it could be achieved through function pointers, but it does not seem to be possible. 我以为可以通过函数指针来实现,但是似乎不可能。 I have been using boost.python to accomplish this. 我一直在使用boost.python来完成此任务。

Say there is a function defined in Python: 假设在Python中定义了一个函数:

def callback(arg1, arg2):
    #do something
    return something

Now I need to pass this function to C++, so that it can be called from there. 现在,我需要将此函数传递给C ++,以便可以从那里调用它。 How do I write the code on C++ side using boost.python to achieve this? 如何使用boost.python在C ++端编写代码以实现此目的?

If it might have any name: 如果可以使用任何名称:

Pass it to a function that takes a boost::python::object . 将其传递给需要boost::python::object

bp::object pycb; //global variable. could also store it in a map, etc
void register_callback(bp::object cb)
{
      pycb = cb;
}

If it is in a single known namespace with a consistent name: 如果它在具有相同名称的单个已知名称空间中:

bp::object pycb = bp::scope("namespace").attr("callback");

bp::object has operator() defined, so you call it just like any function bp::object定义了operator() ,因此您可以像调用任何函数一样调用它

ret = pycb()

Not a clue. 没头绪。 But you can use PyObject_Call() to call it once you have the function object. 但是一旦有了函数对象,就可以使用PyObject_Call()调用它。

我以前没有使用过它,但是参考手册中有一个名为“ 调用Python函数和方法”的部分 ,似乎在演示如何做到这一点。

I used PyRun_SimpleString("myFunction()") as quick hack, as my function's name was known, took no args and lived in the __main__ namespace. 我使用PyRun_SimpleString("myFunction()")作为快捷技巧,因为我知道函数的名称,没有参数,并且位于__main__命名空间中。 Note you additionally need to get lock GIL if you are multi-threaded. 请注意,如果您是多线程的,则还需要获取锁GIL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM