Cython使用unordered_map缓存方法运行时触发段错误,求排查
Cython缓存实现段错误问题排查
我尝试在Cython中实现一个简单的缓存方法,编译通过但运行时读取缓存会导致程序崩溃(段错误)。
以下是我的Cython文件hello.pyx:
# disutils: language = C++ # define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION cimport libc.stdint cimport cython cimport numpy as np from libc.stdio cimport printf from libcpp.unordered_map cimport unordered_map from libcpp.pair cimport pair from cython.operator cimport dereference np.import_array() # needed to initialize numpy-API cdef class DemoClass: cdef readonly unordered_map[double, double[:]] cache def __init__(self): cdef unordered_map[double, double[:]] cache self.cache = cache cpdef double[:] demoMethod(self, double key): if self.cache.count(key) > 0: printf("second time") return self.cache[key] printf("First time") cdef double[:] result = cnp_empty(100) self.cache[key] = result return result
我在Python中执行的代码如下:
from hello import DemoClass import numpy as np demoObj2 = DemoClass() print(demoObj2.demoMethod(0.0)) # <MemoryView of 'ndarray' object> print(demoObj2.demoMethod(0.0)) # this results in Segmentation fault, no more messages
请问我对unordered_map的使用哪里有误?
编辑补充:受David的回答启发,我做了如下测试:
from hello import DemoClass import numpy as np demoObj2 = DemoClass() a = demoObj2.demoMethod(0.0) print(a) # <MemoryView of 'ndarray' object> print(demoObj2.demoMethod(0.0)) # this works fine now, because the reference to the memoryview is now kept, in python.
内容的提问来源于stack exchange,提问作者feiyang472
相关产品推荐
相关产品推荐

