我使用以下代码尝试使用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'
如果没有字典,这可以工作,但我认为字典对于我的用例是必需的。有没有办法使这项工作?
我不想复制来回的向量,因为这些向量将长达数千万个条目。也许我可以存储指向矢量的指针?
答案 0 :(得分:4)
C ++向量在Cython / Python边界线自动转换为list
(因此您看到的错误消息)。 Python dict期望存储Python对象而不是C ++向量。创建一个包含C ++ Vector的cdef class
并将其放入dict中:
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