You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 15:05:26