Python Cython:C++;在字典中使用向量?
我使用下面的代码尝试使用C++向量:Python Cython:C++;在字典中使用向量?,python,c++,cython,Python,C++,Cython,我使用下面的代码尝试使用C++向量: from libcpp.vector cimport vector cdef struct StartEnd: long start, end cdef vector[Sta
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'对象没有属性“push_back”
如果没有字典,则此操作有效,但我认为字典对于我的用例是必要的。有没有办法让这一切顺利进行
我不想来回复制向量,因为这些向量将有几千万个条目长。也许我可以将指针存储到向量中,而不是.< /p> < p>在Cython/Python边界上,C++向量自动转换为<代码>列表>代码(因此,您看到的错误消息)。Python DICT期望存储Python对象,而不是C++向量。创建一个包含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
“如果没有字典,这是什么意思?”@RNar推测
vect.push\u back(…)
有效,但是k['hi'])。push\u back(…)
无效。尝试使用(k['hi'])将k['hi]
转换为向量。push\u back(…)
,如是。回答得很好,谢谢。我通过公开wrapped_vector变量,然后执行打印(k['hi'].wrapped_vector[I])
来完成查找部分的工作。请记住,这样做会将向量复制到临时列表中(这可能会很慢!)。在VecHolder
上定义一个\uuuuu getitem\uuuuuuuuuuuuuuuuuuuuuux)
以避免这种情况(尽管您仍然需要考虑如何打印StartEnd
)。谢谢,我这样做了,效果很好。但有一件事很奇怪:当我直接使用StartEnd结构时,我通过点访问组件(例如,j.start=I
),然而,当我从向量中获取结构时,它是一个字典,我必须这样访问:k['hi'][I]['start']
,而不是k['hi'][I]。start
。我还不确定这是否意味着出了什么问题(即结构已被转换为python对象,而不是保留为C结构。有什么想法吗?是的,它正在转换为与结构匹配的python字典。我没有意识到它会这样做!最大的问题是k['hi'][I]['start']=5
实际上不会改变任何东西。我认为有两种解决方案:1)使用wrapped_vector
(您可能需要使用两行typecastcdef veccholder vh=k['hi'];k['hi'].wrapped_vector[I]。开始)或者2)-您有\uuu getitem\uuu
在StartEnd
周围返回一个小包装器,它存储对VecHolder
和索引的引用,并使用属性访问底层的开始
和结束
(有关实现,请参阅PyPeak2
,忽略“移动”内容)。把这类事情做好,结果总是比看上去更麻烦!