如何将 boost::python::iterator 与 return_internal_reference 一起使用?

2024-03-30

我有课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,第四行是通过getter方法打印的Type。所以不知何故boost::python以这样的方式包装所有内容:

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

这么清楚return_internal_reference其行为与所述不同(请注意,它实际上只是 typedef 结束with_custodian_and_ward_postcall<>) 只要方法调用的结果被引用,它就应该保留对象。

所以我的问题是如何将这样的迭代器暴露给Pythonboost::python?

edit:

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


If 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 boost::python::iterator 与 return_internal_reference 一起使用? 的相关文章

  • 如何捕获未发送到 stdout 的命令行文本?

    我在项目中使用 LAME 命令行 mp3 编码器 我希望能够看到某人正在使用什么版本 如果我只执行 LAME exe 而不带参数 我会得到 例如 C LAME gt LAME exe LAME 32 bits version 3 98 2
  • Python 属性和 Swig

    我正在尝试使用 swig 为一些 C 代码创建 python 绑定 我似乎遇到了一个问题 试图从我拥有的一些访问器函数创建 python 属性 方法如下 class Player public void entity Entity enti
  • 将 Long 转换为 DateTime 从 C# 日期到 Java 日期

    我一直尝试用Java读取二进制文件 而二进制文件是用C 编写的 其中一些数据包含日期时间数据 当 DateTime 数据写入文件 以二进制形式 时 它使用DateTime ToBinary on C 为了读取 DateTime 数据 它将首
  • 打破 ReadFile() 阻塞 - 命名管道 (Windows API)

    为了简化 这是一种命名管道服务器正在等待命名管道客户端写入管道的情况 使用 WriteFile 阻塞的 Windows API 是 ReadFile 服务器已创建启用阻塞的同步管道 无重叠 I O 客户端已连接 现在服务器正在等待一些数据
  • IQueryable 单元或集成测试

    我有一个 Web api 并且公开了一个端点 如下所示 api 假期 name name 这是 Web api 的控制器 get 方法 public IQueryable
  • 为什么从字典中获取时会得到 Action<> 的克隆?

    我有以下字典 private Dictionary
  • 在视口中查找 WPF 控件

    Updated 这可能是一个简单或复杂的问题 但在 wpf 中 我有一个列表框 我用一个填充数据模板从列表中 有没有办法找出特定的数据模板项位于视口中 即我已滚动到其位置并且可以查看 目前我连接到了 listbox ScrollChange
  • 在 NaN 情况下 to_string() 可以返回什么

    我使用 VS 2012 遇到了非常令人恼火的行为 有时我的浮点数是 NaN auto dbgHelp std to string myFloat dbgHelp最终包含5008角色 你不能发明这个东西 其中大部分为0 最终结果是 0 INF
  • 如何在 C 中安全地声明 16 位字符串文字?

    我知道已经有一个标准方法 前缀为L wchar t test literal L Test 问题是wchar t不保证是16位 但是对于我的项目 我需要16位wchar t 我还想避免通过的要求 fshort wchar 那么 C 不是 C
  • 在mysql连接字符串中添加应用程序名称/程序名称[关闭]

    Closed 这个问题需要细节或清晰度 help closed questions 目前不接受答案 我正在寻找一种解决方案 在连接字符串中添加应用程序名称或程序名称 以便它在 MySQL Workbench 中的 客户端连接 下可见 SQL
  • 高效列出目录中的所有子目录

    请参阅迄今为止所采取的建议的编辑 我正在尝试使用 WinAPI 和 C 列出给定目录中的所有目录 文件夹 现在我的算法又慢又低效 使用 FindFirstFileEx 打开我正在搜索的文件夹 然后我查看目录中的每个文件 使用 FindNex
  • 等待 IAsyncResult 函数直至完成

    我需要创建等待 IAsyncResult 方法完成的机制 我怎样才能做到这一点 IAsyncResult result contactGroupServices BeginDeleteContact contactToRemove Uri
  • 检测到严重错误 c0000374 - C++ dll 将已分配内存的指针返回到 C#

    我有一个 c dll 它为我的主 c 应用程序提供一些功能 在这里 我尝试读取一个文件 将其加载到内存 然后返回一些信息 例如加载数据的指针和内存块的计数到 c Dll 成功将文件读取到内存 但在返回主应用程序时 程序由于堆损坏而崩溃 检测
  • 使 Guid 属性成为线程安全的

    我的一个类有一个 Guid 类型的属性 该属性可以由多个线程同时读写 我的印象是对 Guid 的读取和写入不是原子的 因此我应该锁定它们 我选择这样做 public Guid TestKey get lock testKeyLock ret
  • String.Empty 与 "" [重复]

    这个问题在这里已经有答案了 可能的重复 String Empty 和 有什么区别 https stackoverflow com questions 151472 what is the difference between string
  • 这个可变参数模板示例有什么问题?

    基类是 include
  • 堆栈是向上增长还是向下增长?

    我在 C 中有这段代码 int q 10 int s 5 int a 3 printf Address of a d n int a printf Address of a 1 d n int a 1 printf Address of a
  • 如何在richtextbox中使用多颜色[重复]

    这个问题在这里已经有答案了 我使用 C windows 窗体 并且有 richtextbox 我想将一些文本设置为红色 一些设置为绿色 一些设置为黑色 怎么办呢 附图片 System Windows Forms RichTextBox有一个
  • 灵气序列解析问题

    我在使用 Spirit Qi 2 4 编写解析器时遇到一些问题 我有一系列键值对以以下格式解析
  • 是否可以在不连接数据库的情况下检索 MetadataWorkspace?

    我正在编写一个需要遍历实体框架的测试库MetadataWorkspace对于给定的DbContext类型 但是 由于这是一个测试库 我宁愿不连接到数据库 它引入了测试环境中可能无法使用的依赖项 当我尝试获取参考时MetadataWorksp

随机推荐