【发布时间】:2021-02-15 07:52:13
【问题描述】:
在 Cython 中,创建 int 的 C++ 向量的 Python 扩展类非常容易
# vector_int.pyx
# distutils: language = c++
from libcpp.stack cimport stack
from libcpp.vector cimport vector
cdef class VectorInt:
cdef vector[int] v
def __cinit__(self, count):
self.v = [0] * count # <-- Works! Allocate variable length of zeros
def set(self, idx, x):
self.v[idx] = x
def get(self, idx):
return self.v[idx]
def test_vector_int_stack():
v = VectorInt(11)
v.set(0, 42)
assert v.get(0) == 42
但是如何创建int的堆栈对象向量的Python扩展类?
# vector_stack_int.pyx
# distutils: language = c++
from libcpp.stack cimport stack
from libcpp.vector cimport vector
cdef class VectorStackInt:
cdef vector[stack[long]] v
def __cinit__(self, count):
for i in range(count):
self.v.push_back((new stack[long]())) # <--- Error here?!
def set(self, idx, x):
self.v[idx].push(x)
def get(self, idx):
return self.v[idx].top()
这会失败,因为new 返回一个指向新堆栈的指针,
Error compiling Cython file:
------------------------------------------------------------
...
cdef vector[stack[long]] v
def __cinit__(self, count):
for i in range(count):
self.v.push_back((new stack[long]())) # <--- Error here?!
^
------------------------------------------------------------
pvtracec/libs/simple.pyx:58:45: Cannot assign type 'stack[long] *' to 'stack[long]'
【问题讨论】:
-
你试过删除
new吗?即正是你在 C++ 中所做的事情 -
是的!我刚刚意识到,正要回答我自己的答案。为什么不将您的评论升级为一些免费积分的答案。
标签: c++ python-3.x cython cythonize