首页 > 解决方案 > Cython:为 cdef extern 函数提供来自 C++ 的类型迭代器

问题描述

我有以下代码,除了(*)之外cdef extern,所有代码都运行良好:unique

from libc.stdint cimport uint32_t
from libcpp.vector cimport vector

ctypedef struct interval:
    uint32_t start
    uint32_t end

ctypedef vector[uint32_t] intvec
ctypedef vector[interval] interval_vector


cdef uint32_t start_end_equal(interval lhs, interval rhs):
  if ((lhs.start == rhs.start) and (lhs.end == rhs.end)):
      return <uint32_t> 1
  else:
      return <uint32_t> 0


cdef extern from "<algorithm>" namespace "std":
    iterator unique(...)


cdef test(interval_vector intervals):
    intervals.erase(unique(intervals.begin(), intervals.end(), start_end_equal))

上面代码的问题是它出错了

Error compiling Cython file:
------------------------------------------------------------
...
  else:
      return <uint32_t> 0


cdef extern from "<algorithm>" namespace "std":
    iterator unique(...)
   ^
------------------------------------------------------------

minimal_example.pyx:21:4: 'iterator' is not a type identifier

我在哪里可以找到迭代器类型来注释我的函数?

其他解决方法也很感激:)

(*) 如果您想知道为什么我根本不使用,from libcpp.algorithm cimport unique请参阅此相关 q

标签: cython

解决方案


自从评论中出现以来,我已经在您的相关问题中回答了这个问题。在这里发布,所以这个问题有一个答案(但是社区 wiki 所以两次没有来自同一件事的声誉)。

您的选择是让迭代器类型成为模板参数(并且不指定函数参数):

cdef extern from "<algorithm>" namespace "std":
    Iter unique[Iter](Iter, Iter, ...)

或者,您可以尝试将其限制为特定的向量迭代器类型。在你的情况下,这是vector[interval].iterator. 这是在 Cython 中作为向量内的嵌套类型包装的。


推荐阅读