Cython:C++ 在字典中使用向量?

Cython: C++ Use a vector in a dictionary?

我正在使用以下代码尝试使用 C++ 向量:

from libcpp.vector cimport vector                                                                                                                                         

cdef struct StartEnd:
    long start, end 

cdef vector[StartEnd] vect
print(type(vect))
cdef int i
cdef StartEnd j
k = {}
k['hi'] = vect
for i in range(10):
    j.start = i 
    j.end = i + 2 
    k['hi'].push_back(j)
for i in range(10):
    print(k['hi'][i])

这里的确切功能并不重要,这只是一个虚拟程序。问题是 运行 这会产生错误: AttributeError: 'list' object has no attribute 'push_back' 如果没有字典,这会起作用,但我认为字典对于我的用例来说是必需的。有没有办法让这个工作?

我不想来回复制向量,因为这些向量将达到数千万个条目的长度。也许我可以存储指向向量的指针?

C++ 向量在 Cython/Python 边界处自动转换为 list(因此您会看到错误消息)。 Python 字典期望存储 Python 对象而不是 C++ 向量。创建一个包含 C++ Vector 的 cdef class 并将其放入字典中:

cdef class VecHolder:
   cdef vector[StartEnd] wrapped_vector

   # the easiest thing to do is add short wrappers for the methods you need
   def push_back(self,obj):
     self.wrapped_vector.push_back(obj)

cdef int i
cdef StartEnd j
k = {}
k['hi'] = VecHolder()
for i in range(10):
   j.start = i 
   j.end = i + 2 
   k['hi'].push_back(j) # note that you're calling 
       # the wrapper method here which then calls the c++ function