Cython:C ++在字典中使用向量? [英] Cython: C++ Use a vector in a dictionary?

查看:82
本文介绍了Cython:C ++在字典中使用向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using the following code to try to work with C++ vectors:

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'如果没有字典,此方法有效,但我认为字典是我的用例所必需的。有什么方法可以使这项工作完成?

The exact functionality here isn't important, this is just a dummy program. The issue is that running this generates the error: AttributeError: 'list' object has no attribute 'push_back' This works if there is no dictionary, but I think that the dictionary is necessary for my use case. Is there a way to make this work?

我不想来回复制向量,因为这些向量的长度将达到数千万。

I do not want to be copying vectors back and forth as these vectors will get to be tens of millions of entries long. Maybe I can store pointers to the vector instead?

推荐答案

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

The C++ vector automatically gets converted to list at the Cython/Python borderline (hence the error message you see). The Python dict expects to store Python objects rather than C++ vectors. Create a cdef class that holds a C++ Vector and put that in the dict instead:

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

这篇关于Cython:C ++在字典中使用向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆