在Cython中使用C++映射

Using C++ Map in Cython

提问人:user58925 提问时间:10/10/2023 最后编辑:user58925 更新时间:10/10/2023 访问量:32

问:

我正在尝试在我的 Cython 代码中使用 C++ 中的地图(本质上是作为替换 Python 字典的一种手段)。这是我的代码:

parameters.pyx 文件

from libcpp.map cimport map
from libcpp.string  cimport string

cdef class Parameters:
    cdef map data[string,int]

    def __init__(self):
        self.data = {{'a', 1}}

    cpdef void change_data(self, dict newdata):
        self.data = newdata

model.pyx 文件

from parameters import Parameters
from libcpp.map cimport map
from libcpp.string  cimport string

cpdef single_run():
    parameters = Parameters()

    cdef map newMap[string,int]
    
    newMap ={{'a',2}}

    parameters.change_data(newMap)

错误: 文件“parameters.pyx”,第 9 行,在参数中。参数。初始化 self.data = {{'a', 1}} TypeError:不可哈希 类型:“set”

这是 setup.py 文件

#!/usr/bin/env python3

from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules=cythonize(["*.py","*.pyx"],
language="c++")
    
)
python c++ 字典 cython stdmap

评论

0赞 Mr Fooz 10/10/2023
Cython 不理解“新”C++ 初始值设定项列表语法。您需要显式插入初始条目,或者将更高级的零件移动到 .pyx 文件引用的 .h 和/或 .cpp 文件中。

答: 暂无答案