Calling Python functions from C++(从 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 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 C++ 调用 Python 函数
基础教程推荐
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- c++ STL设置差异 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
