<分区>
我有一个 C++ 函数 Obj *new_object(const char *name)
。它返回一个从私有(private)池中分配的新对象。该对象应由 free_object(Obj *obj)
释放(不由 free() 或 delete 释放)。我如何安排我的 boost.python 包装器,以便当 python obj 超出范围(并调用 gc)时将调用 free_obj
?
<分区>
我有一个 C++ 函数 Obj *new_object(const char *name)
。它返回一个从私有(private)池中分配的新对象。该对象应由 free_object(Obj *obj)
释放(不由 free() 或 delete 释放)。我如何安排我的 boost.python 包装器,以便当 python obj 超出范围(并调用 gc)时将调用 free_obj
?
最佳答案
我认为最方便的方法是确保您的 Boost.Python 类声明包含 Obj
和 boost::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/