C ++析构函数调用boost :: python包装对象

时间:2016-07-06 15:45:06

标签: python c++ boost-python

boost :: python是否提供了C ++析构函数的保证 考虑到达零的时刻,调用包裹对象 相应python对象的引用计数?

我担心一个C ++对象会打开一个文件进行编写,并在其析构函数中执行文件关闭。是否保证在删除对象的所有python引用或超出范围时写入文件?

我的意思是:

A=MyBoostPythonObject()
del A # Is the C++ destructor of MyBoostPythonObject called here?

我的经验表明,析构函数总是在此时调用,但无法找到任何保证。

1 个答案:

答案 0 :(得分:3)

Boost.Python保证如果Python对象拥有包装的C ++对象的所有权,那么当删除Python对象时,将删除包装的C ++对象。 Python对象的生命周期由Python决定,其中当对象的引用计数达到零时,对象可能立即被销毁。对于非简化情况,例如循环引用,对象将由垃圾收集器管理,可能在程序退出之前被销毁。

一个Pythonic解决方案可能是公开实现context manager protocol的类型。内容管理器协议由一对方法组成:一个在进入运行时上下文时将被调用,另一个在退出运行时上下文时将被调用。通过使用上下文管理器,可以控制文件打开的范围。

>>> with MyBoostPythonObject() as A:  # opens file.
...     A.write(...)                  # file remains open while in scope.
...                                   # A destroyed once context's scope is exited.

以下示例demonstrating将一个RAII类型的类暴露给Python作为上下文管理器:

#include <boost/python.hpp>
#include <iostream>

// Legacy API.
struct spam
{
  spam(int x)    { std::cout << "spam(): " << x << std::endl;   }
  ~spam()        { std::cout << "~spam()" << std::endl;         }
  void perform() { std::cout << "spam::perform()" << std::endl; }
};

/// @brief Python Context Manager for the Spam class.
class spam_context_manager
{
public:

  spam_context_manager(int x): x_(x) {}

  void perform() { return impl_->perform(); }

// context manager protocol
public:

  // Use a static member function to get a handle to the self Python
  // object.
  static boost::python::object enter(boost::python::object self)
  {
    namespace python = boost::python;
    spam_context_manager& myself =
      python::extract<spam_context_manager&>(self);

    // Construct the RAII object.
    myself.impl_ = std::make_shared<spam>(myself.x_);

    // Return this object, allowing caller to invoke other
    // methods exposed on this class.
    return self;
  }

  bool exit(boost::python::object type,
            boost::python::object value,
            boost::python::object traceback)
  {
    // Destroy the RAII object.
    impl_.reset();
    return false; // Do not suppress the exception.
  }
private:
  std::shared_ptr<spam> impl_;
  int x_;
};


BOOST_PYTHON_MODULE(example)
{
  namespace python = boost::python;
  python::class_<spam_context_manager>("Spam", python::init<int>())
    .def("perform", &spam_context_manager::perform)
    .def("__enter__", &spam_context_manager::enter)
    .def("__exit__", &spam_context_manager::exit)
    ;
}

交互式使用:

>>> import example
>>> with example.Spam(42) as spam:
...     spam.perform()
...
spam(): 42
spam::perform()
~spam()