如何在 cython 中使用unordered_map

How to use unordered_map in cython?

本文关键字:unordered map cython      更新时间:2023-10-16

我想要一个分步指南,如何在cython中使用unordered_map。

我已经将文件

unordered_map.pxd 从 https://gist.github.com/ikuyamada/3265267 包含到 Cython/Include/libcpp 中,并使用了其他 3 个文件:

main.py:

import pyximport;
pyximport.install()
from foo import F
F()

foo.pyx:

from libcpp.unordered_map cimport unordered_map

def F():
    cdef unordered_map[int, int] my_map
    my_map[1]=11
    my_map[2]=12
    print my_map[1],my_map[2]

foo.pyxbld:(将foo.pyx编译成C++)

def make_ext(modname, pyxfilename):
    from distutils.extension import Extension
    return Extension(name=modname,
                     sources=[pyxfilename],
                     language='C++')

当我运行 test.py 时,出现错误:

foo.cpp
C:Program Files (x86)Microsoft Visual Studio 9.0VCINCLUDExlocale(342) : warning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc
C:Userskitov.pyxbldtemp.win-amd64-2.7Releasepyrexfoo.cpp(316) : fatal error C1083: Cannot open include file: 'tr1/unordered_map': No such file or directory

我使用Win7,Python 2.7 64位,VS2008 Professional。

如果你已经编译了foo,我认为你不需要运行pyximport.install()。这可能会搞砸它,因为pyximport重新编译源代码,但您没有向pyximport提供任何编译器参数,因此它使用默认设置编译(即不知道foo是 cpp 源文件)。

main.py:

from foo import F
F()

foo.pyx:<--不要忘记x-

#distutils: language = c++
from libcpp.unordered_map cimport unordered_map
def F():
    cdef unordered_map[int, int] my_map
    my_map[1]=11
    my_map[2]=12
    print my_map[1],my_map[2]

我已经解决了这个问题:

1) 我需要从 http://www.microsoft.com/en-us/download/details.aspx?id=6922 安装 Visual C++ 2008 功能包

2)我需要使用以下unordered_map.pxd:

from libcpp.utility cimport pair
cdef extern from "<unordered_map>" namespace "std::tr1":
    cdef cppclass unordered_map[T, U]:
        cppclass iterator:
            pair[T, U]& operator*() nogil
            iterator operator++() nogil
            iterator operator--() nogil
            bint operator==(iterator) nogil
            bint operator!=(iterator) nogil
        unordered_map()
        unordered_map(unordered_map&)
        U& operator[](T&) nogil
        # unordered_map& operator=(unordered_map&)
        U& at(T&) nogil
        iterator begin() nogil
        void clear() nogil
        size_t count(T&) nogil
        bint empty() nogil
        iterator end() nogil
        pair[iterator, iterator] equal_range(T&) nogil
        void erase(iterator) nogil
        void erase(iterator, iterator) nogil
        size_t erase(T&) nogil
        iterator find(T&) nogil
        pair[iterator, bint] insert(pair[T, U]) nogil
        iterator insert(iterator, pair[T, U]) nogil
        void insert(input_iterator, input_iterator)
        size_t max_size() nogil
        void rehash(size_t)
        size_t size() nogil
        void swap(unordered_map&) nogil

与 https://gist.github.com/ikuyamada/3265267 相比,更改了一行:

cdef extern from "<tr1/unordered_map>" namespace "std::tr1": 

->

cdef extern from "<unordered_map>" namespace "std::tr1":