如何从 swig C++ 引发 StopIteration代码?

发布于 2024-12-05 11:30:24 字数 385 浏览 0 评论 0 原文

我正在尝试通过在类上实现 python 迭代协议来扩展 C++ 库。问题是,尝试从 next() 方法引发 StopIteration 异常会使程序出现 SegFault。我用于从 C++ 代码(在 python.i 中)引发异常的方法是此处描述的方法:http://www.swig.org/Doc1.3/Python.html#Python_nn44

虽然该列表没有列出 StopIteration 异常,但这就是我尝试过的:

PyErr_SetString(PyExc_StopIteration, NULL);

I'm trying to extend a C++ library by implementing the python iteration protocol on a class. The problem is that trying to raise a StopIteration exception from the next() method makes the program SegFault. The method I've used for raising the exception from the C++ code (in python.i) is the one described here: http://www.swig.org/Doc1.3/Python.html#Python_nn44

Although that list doesn't have the StopIteration exception listed this is what I've tried:

PyErr_SetString(PyExc_StopIteration, NULL);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我ぃ本無心為│何有愛 2024-12-12 11:30:24

因此,正确的答案似乎是 next() 方法必须返回 PyObject* 并且还使用 SetNone。所以它看起来像这样:

PyObject* next(PyObject* self) {
  if (i < n) {
         \\ go on iterating
  } else {
         PyErr_SetNone(PyExc_StopIteration);
         return NULL;
  }
}

感谢 aix 提供的链接!

So the right answer seems to be that the next() method must return a PyObject* and also use SetNone. So it would look like this:

PyObject* next(PyObject* self) {
  if (i < n) {
         \\ go on iterating
  } else {
         PyErr_SetNone(PyExc_StopIteration);
         return NULL;
  }
}

Thanks to aix for the link!

咆哮 2024-12-12 11:30:24

段错误几乎肯定是由您传递给 PyErr_SetString 的 NULL 指针引起的。请尝试以下操作:

PyErr_SetString(PyExc_StopIteration, "end of collection");

编辑我刚刚看到以下精彩的帖子,您可能会发现它很有用:如何使用 Python C API 创建生成器/迭代器?

The segfault is almost certainly caused by the NULL pointer you've passing to PyErr_SetString. Try the following instead:

PyErr_SetString(PyExc_StopIteration, "end of collection");

edit I've just come across the following excellent post, which you may find useful: How to create a generator/iterator with the Python C API?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文