【问题标题】:How to use boost::python::iterator with return_internal_reference?如何将 boost::python::iterator 与 return_internal_reference 一起使用?
【发布时间】:2012-07-02 20:14:45
【问题描述】:

我有一个类Type,它不能被复制,也不包含默认构造函数。 我有第二类A,它充当上述类的集合。第二个类通过迭代器提供访问权限,而我的迭代器具有取消引用运算符:

class A {
    class iterator {
        [...]
      public:
        Type & operator*()
        { 
            return instance;
        }
      private:
        Type instance;
    }
    [...]
};

现在公开我写了一个看起来像这样的boost::python代码:

class_<A>("A", [...])
    .def("__iter__", iterator<A, return_internal_reference<> >())
    .def("__len__", container_length_no_diff<A, A::iterator>)
;

将打印消息添加到 Python 代码的所有迭代器操作(构造、赋值、取消引用、销毁)后,如下所示:

for o in AInstance:
    print o.key

我得到输出(修剪到重要部分):

construct 0xffffffff7fffd3e8
dereference: 0xffffffff7fffd3e8
destroy 0xffffffff7fffd3e8
get key 0xffffffff7fffd3e8

在上面的代码中,这些地址只是instance 成员的地址(或方法调用中的this)。 前三行由iterator 生成,第四行由Type 中的getter 方法打印。所以不知何故 boost::python 以这样的方式包装所有内容:

  1. 创建迭代器
  2. 取消引用迭代器并存储引用
  3. 销毁迭代器(及其包含的对象)
  4. 使用第二步获得的参考

很明显,return_internal_reference 的行为不像声明的那样(注意它实际上只是 with_custodian_and_ward_postcall&lt;&gt; 上的 typedef),只要引用了方法调用的结果,它就应该保留对象。

所以我的问题是如何使用boost::python 向 Python 公开这样的迭代器?

编辑:

正如有人指出的那样,可能不清楚:原始容器不包含Type 类型的对象。它包含一些BaseType 对象,我可以从中构造/修改Type 对象。所以上面例子中的iterator就像transform_iterator一样。

【问题讨论】:

    标签: c++ boost reference boost-python


    【解决方案1】:

    如果A 是拥有Type 实例的容器,则考虑让A::iterator 包含Type 的句柄而不是Type

    class iterator {
      [...]
    private:
      Type* instance; // has a handle to a Type instance.
    };
    

    代替:

    class iterator {
      [...]
    private:
      Type instance; // has a Type instance.
    };
    

    在 python 中,迭代器将包含对其迭代的容器的引用。这将延长可迭代对象的生命周期,并防止可迭代对象在迭代过程中被垃圾回收。

    >>> from sys import getrefcount
    >>> x = [1,2,3]
    >>> getrefcount(x)
    2 # One for 'x' and one for the argument within the getrefcount function.
    >>> iter = x.__iter__()
    >>> getrefcount(x)
    3 # One more, as iter contains a reference to 'x'.
    

    boost::python 支持这种行为。这是一个示例程序,Foo 是一个无法复制的简单类型; FooContainer 是一个可迭代的容器; FooContainer::iterator 是一个迭代器:

    #include <boost/python.hpp>
    #include <iterator>
    
    // Simple example type.
    class Foo
    {
    public:
      Foo()  { std::cout << "Foo constructed: " << this << std::endl; }
      ~Foo() { std::cout << "Foo destroyed:   " << this << std::endl; }
      void set_x( int x ) { x_ = x;    }
      int  get_x()        { return x_; }
    private:
      Foo( const Foo& );            // Prevent copy.
      Foo& operator=( const Foo& ); // Prevent assignment.
    private:
      int x_;  
    };
    
    // Container for Foo objects.
    class FooContainer
    {
    private:
      enum { ARRAY_SIZE = 3 };
    public:
      // Default constructor.
      FooContainer()
      {
        std::cout << "FooContainer constructed: " << this << std::endl;
        for ( int i = 0; i < ARRAY_SIZE; ++i )
        {
          foos_[ i ].set_x( ( i + 1 ) * 10 );
        }
      }
    
      ~FooContainer()
      {
        std::cout << "FooContainer destroyed:   " << this << std::endl;
      }
    
      // Iterator for Foo types.  
      class iterator
        : public std::iterator< std::forward_iterator_tag, Foo >
      {
        public:
          // Constructors.
          iterator()                      : foo_( 0 )        {} // Default (empty).
          iterator( const iterator& rhs ) : foo_( rhs.foo_ ) {} // Copy.
          explicit iterator(Foo* foo)     : foo_( foo )      {} // With position.
    
          // Dereference.
          Foo& operator*() { return *foo_; }
    
          // Pre-increment
          iterator& operator++() { ++foo_; return *this; }
          // Post-increment.     
          iterator  operator++( int )
          {
            iterator tmp( foo_ );
            operator++();
            return tmp;
          }
    
          // Comparison.
          bool operator==( const iterator& rhs ) { return foo_ == rhs.foo_; }
          bool operator!=( const iterator& rhs )
          {
            return !this->operator==( rhs );
          }
    
        private:
          Foo* foo_; // Contain a handle to foo; FooContainer owns Foo.
      };
    
      // begin() and end() are requirements for the boost::python's 
      // iterator< container > spec.
      iterator begin() { return iterator( foos_ );              }
      iterator end()   { return iterator( foos_ + ARRAY_SIZE ); }
    private:
      FooContainer( const FooContainer& );            // Prevent copy.
      FooContainer& operator=( const FooContainer& ); // Prevent assignment.
    private:
      Foo foos_[ ARRAY_SIZE ];
    };
    
    BOOST_PYTHON_MODULE(iterator_example)
    {
      using namespace boost::python;
      class_< Foo, boost::noncopyable >( "Foo" )
        .def( "get_x", &Foo::get_x )
        ;
      class_< FooContainer, boost::noncopyable >( "FooContainer" )
        .def("__iter__", iterator< FooContainer, return_internal_reference<> >())
        ;
    }
    

    这是示例输出:

    >>> from iterator_example import FooContainer
    >>> fc = FooContainer()
    Foo constructed: 0x8a78f88
    Foo constructed: 0x8a78f8c
    Foo constructed: 0x8a78f90
    FooContainer constructed: 0x8a78f88
    >>> for foo in fc:
    ...   print foo.get_x()
    ... 
    10
    20
    30
    >>> fc = foo = None
    FooContainer destroyed:   0x8a78f88
    Foo destroyed:   0x8a78f90
    Foo destroyed:   0x8a78f8c
    Foo destroyed:   0x8a78f88
    >>> 
    >>> fc = FooContainer()
    Foo constructed: 0x8a7ab48
    Foo constructed: 0x8a7ab4c
    Foo constructed: 0x8a7ab50
    FooContainer constructed: 0x8a7ab48
    >>> iter = fc.__iter__()
    >>> fc = None
    >>> iter.next().get_x()
    10
    >>> iter.next().get_x()
    20
    >>> iter = None
    FooContainer destroyed:   0x8a7ab48
    Foo destroyed:   0x8a7ab50
    Foo destroyed:   0x8a7ab4c
    Foo destroyed:   0x8a7ab48
    

    【讨论】:

    • 所以我自己想出了一样。我认为纯粹的Type* instance; 也很难追踪,而某种共享指针是一种更好的方法。尤其是boost::python(几乎?)毫不费力地支持它。此外,这种方法也有一个缺点,即分配会减慢速度,因此我最终实现了复制构造函数并按值返回(尽管我必须进行一些测试以确保它比为指针分配数据更快)。跨度>
    • 我认为你完全没有抓住重点。我有某种transform_iterator。我要返回的对象实例在任何地方都不存在。容器不包含Type 的对象,而是允许我构造Type 的对象。
    • @elmo:您可能需要考虑更新原始问题以反映这些要求/意图,因为目前没有提及transform_iterator,并且有人建议Type您要返回的对象包含在 A 中。
    【解决方案2】:

    我认为整个问题在于我没有完全理解 iterator 类应该提供什么语义。 似乎只要容器存在,迭代器返回的值就必须是有效的,而不是迭代器。

    这意味着boost::python 行为正确,对此有两种解决方案:

    • 使用boost::shared_ptr
    • 按值返回

    比我尝试做的方法效率低一些,但看起来没有其他方法。

    编辑: 我已经制定了一个解决方案(不仅可能,而且看起来效果很好):Boost python container, iterator and item lifetimes

    【讨论】:

      【解决方案3】:

      以下是相关示例: https://wiki.python.org/moin/boost.python/iterator.
      您可以通过 const / non const reference返回迭代器值

      ...
      .def("__iter__"
           , range<return_value_policy<copy_non_const_reference> >(
                 &my_sequence<heavy>::begin
               , &my_sequence<heavy>::end))
      

      想法是,正如您所提到的,您应该绑定到容器生命周期而不是返回值的迭代器生命周期。

      【讨论】:

        猜你喜欢
        • 2015-01-15
        • 2018-05-13
        • 1970-01-01
        • 1970-01-01
        • 2021-10-02
        • 2021-05-06
        • 2017-12-27
        • 2017-08-13
        • 1970-01-01
        相关资源
        最近更新 更多