递归过程中cython libcpp.vector分段错误

时间:2012-03-31 22:58:56

标签: python cython

vector during a recursion to push_back`来自某个类的一些实例,但遗憾的是我得到了一个分段错误。

这是一个简化版本,也会出现此错误:

pyx文件

from libcpp.vector cimport vector
from cython.operator cimport dereference as deref, preincrement as inc


cdef class Grid:
    cdef unsigned int srow
    cdef unsigned int erow
    cdef unsigned int scol
    cdef unsigned int ecol

    def __init__(self, unsigned int srow, unsigned int erow, unsigned int scol,
            unsigned int ecol):
        self.srow = srow
        self.erow = erow
        self.scol = scol
        self.ecol = ecol



cdef simple_function_c(vector[Grid] &vp , unsigned int counter):

    cdef Grid p

    if counter == 10:
        return

    p = Grid(counter-1, counter, counter-1 , counter+1)
    vp.push_back(p)
    counter += 1
    simple_function_c(vp, counter)

def simple_function():

    cdef vector[Grid] vp
    cdef unsigned int counter
    cdef Grid tp

    counter = 0
    simple_function_c(vp, counter)

    print vp.size() #this works and outputs 10

    cdef vector[Grid].iterator it = vp.begin()
    while it != vp.end():
        tp =  deref(it) #Seg FAUL !!!
        print tp.srow, tp.erow, tp.scol, tp.ecol
        inc(it)

py文件

from testrec import simple_function
simple_function()

setup.py

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

setup(ext_modules=[Extension(
                   "testrec",
                   ["testrec.pyx"],
                   language="c++")],
      cmdclass={'build_ext': build_ext})

我不知道为什么会这样。我注意到,当班级只有两个字段时,我没有得到段错:非常奇怪

1 个答案:

答案 0 :(得分:0)

更新:修复只做

cdef struct Grid:
     unsigned int srow
     unsigned int erow
     unsigned int scol
     unsigned int ecol