Search code examples
pythonc++cythonmissing-dataordered-map

How to use unordered_map in cython?


I want a step by step guide, how to use unordered_map in cython.

I've included file unordered_map.pxd into Cython/Includes/libcpp from https://gist.github.com/ikuyamada/3265267 and use 3 other files:

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: (to compile foo.pyx into C++)

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

When I run test.py, I get error:

foo.cpp
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\INCLUDE\xlocale(342) : warning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc
C:\Users\kitov\.pyxbld\temp.win-amd64-2.7\Release\pyrex\foo.cpp(316) : fatal error C1083: Cannot open include file: 'tr1/unordered_map': No such file or directory

I use Win7, Python 2.7 64bit, VS2008 Professional.


Solution

  • I've solved the problem:

    1) I needed to install Visual C++ 2008 Feature Pack from http://www.microsoft.com/en-us/download/details.aspx?id=6922

    2) I needed to use the following 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
    

    One line was changed, compared to https://gist.github.com/ikuyamada/3265267:

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

    ->

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