从 C++ 调用 Python 函数

2022-01-03 00:00:00 python callback c++ boost-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 定义了 operator(),所以你可以像调用任何函数一样调用它

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

ret = pycb()

相关文章