如何使用 pybind11 将 python 函数保存到静态 c++ 容器中?
How can I save a python function to a static c++ container using pybind11?
本质上,在C++端,我有一个包含某种类型函数的容器。现在我想向 python 公开这个容器,以便用户提供自己的 python 函数。
最简单的示例如下所示:
#include "pybind/common/Common.h"
using CppFunc = std::function< int (int) >;
PYBIND11_MODULE( test, m )
{
m.def("addFunc", [](const pybind11::function& f){
static std::vector<CppFunc> vec{};
vec.push_back(f.cast<CppFunc>());
});
}
然后在python中,我想做这样的事情。
import test
def myFunc(number):
return number+1
test.addFunc(myFunc)
有趣的是,这工作正常。但是,如果我使用"python script.py"运行脚本,它会运行,然后永远不会终止。在交互式控制台中,相同的代码可以正常工作,直到您尝试关闭控制台:进程卡住。
如何安全地将此 python 函数存储在C++容器中?
>static std::vector<CppFunc> vec{}
存储对python对象(用户函数(的引用,这些对象由于静态存储而永远不会被释放,因此解释器不能终止。
为了确保解释器终止,您可以在模块终止时调用清理函数:
#include "pybind11/pybind11.h"
#include "pybind11/functional.h"
namespace py = pybind11;
using CppFunc = std::function< int (int) >;
PYBIND11_MODULE( test , m )
{
static std::vector<CppFunc> vec{};
m.def("addFunc", [](CppFunc f){
vec.push_back(std::move(f));
});
m.add_object("_cleanup", py::capsule([]{ vec.clear(); }));
}
有关更多详细信息,请参阅文档:https://pybind11.readthedocs.io/en/stable/advanced/misc.html#module-destructors
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- #为""定义宏;静态";针对不同的上下文
- cmake如何在fedora工作站中找到boost静态库包
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 将公共但非静态的成员函数与ALGLIB集成
- cmake在我的项目中所需的所有静态库都不成功
- C++从另一个类访问公共静态向量的正确方法是什么
- 基于boost的程序的静态链接——zlib问题
- 在静态库中嵌入类方法
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 如何在C++中获得"静态纯虚拟"功能?
- 私有类型的静态常量成员
- 使用gcc从静态链接的文件中查找可选符号
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 如何在C++中使用非静态成员函数作为回调函数
- 将静态库链接到不带-fPIC的共享库中
- 静态结构和一个定义规则
- 为什么虚函数不能是静态的和全局的?
- C++17中函数模板中的静态数组初始化(MSVC 2019)
- 停止cmake target_link_libraries将插件中静态库的两个对象文件链接到静态库本身