Using C++ STL maps in Cython

2019-07-24 00:10发布

I'm trying to use a map in a Cython class but the Cython compiler raises an error.

Here is an example demonstrating my problem and the error reported by Cython.

Cython file pyx

from libcpp.map cimport map
from libcpp.utility cimport pair
from libcpp.string  cimport string

cdef class MyDict:
      cdef:
            map[string, int] components

      def __setitem__(self, key, value):
            self.components[key] = value

      def __getitem__(self, key):
            return self.components[key]

Python file

from pyximport import install
install()

from dic_class import MyDict

m = MyDict()

m["home"] = 5

print m["home"]

Error reported by Cython

fatal error: utility: No such file or directory

标签: maps cython
1条回答
淡お忘
2楼-- · 2019-07-24 00:20

You've not done anything to set it up to compile as C++ rather than C. The C compiler will be unable to find the C++ standard library (hence the "no such file or directory" error).

You need to tell pyximport to use C++ instead of C by setting up a .pyxbld file. Alternatively you could use setup.py in C++ mode instead of pyximport.

查看更多
登录 后发表回答