python - 我如何让 boost.python 调用函数来释放对象?

标签 python c++ boost boost-python

<分区>

我有一个 C++ 函数 Obj *new_object(const char *name)。它返回一个从私有(private)池中分配的新对象。该对象应由 free_object(Obj *obj) 释放(由 free() 或 delete 释放)。我如何安排我的 boost.python 包装器,以便当 python obj 超出范围(并调用 gc)时将调用 free_obj

最佳答案

我认为最方便的方法是确保您的 Boost.Python 类声明包含 Objboost::shared_ptr<Obj> .

然后,使用 boost::python::make_constructor在构造时实例化对象。您返回的boost::shared_ptr<Obj>应该设置自己的析构函数(在您的情况下为 free_object() )。这是此解决方案的草图:

static boost::shared_ptr<Obj> init_from_c_string(const char* name) {
  //set destructor upon shared pointer initialisation
  return boost::shared_ptr<Obj>(new_object(name), &free_object);
}

//at your module scope, declare "Obj" like this
using namespace boost::python;
class_<Obj, boost::shared_ptr<Obj>>("Obj", "Obj docstring", no_init)
    .def("__init__", make_constructor(&init_from_c_string, default_call_policies(), (arg("name"))), "Constructs a new object with a given name.")
    //other .def and similar
;

关于python - 我如何让 boost.python 调用函数来释放对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21609094/

相关文章:

python - 是否有内置函数可以执行 numpy.fromstring 的相反操作?

python - 如何导入安装在主目录中的模块?

python - 使用现有数据框的分组比率构建新的数据框

模板的c++模板

linux - 在 ubuntu core 14.04 上安装 libboost-all-dev 时依赖性失败

c++ - Boost asio 与标准输入混淆?

python - Django 分组查询

c++ - 未定义对 'boost::system::generic_category()' 的引用?

c++ - Python逐行从子进程捕获stdout

c++ - Boost tcp stream with filtering input stream 导致挂起