python - Cython:C++ 在字典中使用 vector ?

标签 python c++ cython

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

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' 如果没有字典,这会起作用,但我认为字典对于我的用例是必需的。有什么办法可以做到这一点吗?

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

最佳答案

C++ vector 在 Cython/Python 边界线处自动转换为 list(因此您会看到错误消息)。 Python 字典期望存储 Python 对象而不是 C++ vector 。创建一个包含 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

关于python - Cython:C++ 在字典中使用 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34298294/

相关文章:

Python 2.7 Socket 编程端口

python - 使用 Multiprocessing 和 PySftp 并行下载

python - 如何在 Python 中显示 jpg 文件?

C++如何扩展一个类并转换为具有相同名称的适当类型

python - 如何在 Cython 中获得内存 View 列表?

cython - 一些标准的 C 库数学运算与 noGIL 不兼容

python - 如何以列表格式获取 spotipy 播放列表结果

c++ - "error:no matching function call to ..."

c++ - 参数列表中间的可变模板参数

class - 如何将属性的文档字符串放入 cython cdef 类中?