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

Mik*_*cre 4 c++ python cython

我正在使用以下代码尝试使用 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])
Run Code Online (Sandbox Code Playgroud)

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

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

Dav*_*idW 6

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

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
Run Code Online (Sandbox Code Playgroud)