从 C++ 调用 Python 函数

2023-10-17C/C++开发问题
3

本文介绍了从 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 定义了 operator(),所以你可以像调用任何函数一样调用它

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

ret = pycb()

这篇关于从 C++ 调用 Python 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6