Python 在cython中使用具有数组值的cpp映射

Python 在cython中使用具有数组值的cpp映射,python,c,cython,Python,C,Cython,我正在尝试构建一个以整数作为键,以整数列表作为值的映射。我已经编写了以下test.pyx文件: from libcpp.map cimport map as cmap import array from libcpp.pair cimport pair as cpair from cpython cimport array cdef cmap[int, int[:]] dict_to_cmap(dict the_dict): cdef int map_key cdef int[

我正在尝试构建一个以整数作为键,以整数列表作为值的映射。我已经编写了以下test.pyx文件:

from libcpp.map cimport map as cmap
import array
from libcpp.pair cimport pair as cpair
from cpython cimport array

cdef cmap[int, int[:]] dict_to_cmap(dict the_dict):
    cdef int map_key
    cdef int[:] map_val
    cdef cpair[int, int[:]] map_element
    cdef cmap[int, int[:]] my_map
    for key,val in the_dict.items():
        map_key = key
        map_val = array.array('i', val)
        map_element = (map_key, map_val)
        my_map.insert(map_element)
    print("values are:")
    print(my_map[1], my_map[1][0])
    print(my_map[2], my_map[2][0])
    return my_map

def test():
    the_dict = {1:[1], 2:[1]}
    dict_to_cmap(the_dict)
当我使用编译此代码时:
python测试\u setup.py build\u ext--inplace

并使用:
python-c“导入测试;test.test()”

结果是:

values are:
(<MemoryView of 'NoneType' at 0x7f018b837be0>, -1954556344)
(<MemoryView of 'NoneType' at 0x7f018b837d88>, 1)
值为:
(, -1954556344)
(, 1)

如您所见,其中一个结果已损坏。我做错了什么?这似乎与
int[:]

Cython memoryview不拥有数据,它只是一个内存视图。你不应该将代码> >数组< /> >传递给C++映射,因为数组< /Cord>对象最终将被Python垃圾收集。这就是为什么你得到了“不看”的结果。那么,谁应该拥有数据并管理参考计数呢C++

这是一个有效的:

from libcpp.map cimport map as cmap
from libcpp.pair cimport pair as cpair
from libcpp.vector cimport vector

cdef cmap[int, vector[int]] dict_to_cmap(dict the_dict):
    cdef int map_key
    cdef vector[int] map_val
    cdef cpair[int, vector[int]] map_element
    cdef cmap[int, vector[int]] my_map
    for key,val in the_dict.items():
        map_key = key
        map_val = val  # list values will be copied to C++ vector
        map_element = (map_key, map_val)
        my_map.insert(map_element)
    return my_map

def test():
    the_dict = {1:[1, 2, 3], 2:[4, 5, 6]}
    print(dict_to_cmap(the_dict))  # Cython will automatically convert the C++ map to a Python dict

这回答了你的问题吗?我不这样认为,但谢谢!谢谢这就是答案!