从C ++调用Python函数

从C ++调用Python函数

问题描述:

我想实现从C ++调用Python函数。我认为它可以通过函数指针实现,但它似乎是不可能的。我一直使用 boost.python 来完成这个。

I am trying to achieve call Python functions from C++. 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.

说在Python中定义了一个函数:

Say there is a function defined in Python:

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

需要将此函数传递给C ++,以便可以从那里调用。如何使用 boost.python 在C ++上编写代码以实现这一点?

Now I need to pass this function to C++, so that it can be called from there. How do I write the code on C++ side using boost.python to achieve this?

如果它可能有任何名称:

If it might have any name:

将它传递给一个 boost :: python :: object 。

Pass it to a function that takes a 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 $ c> operator()定义,所以你像任何函数一样调用它

bp::object has operator() defined, so you call it just like any function

ret = pycb()