Skip to content

Instantly share code, notes, and snippets.

@hryk
Created October 22, 2012 12:28
Show Gist options
  • Save hryk/3931291 to your computer and use it in GitHub Desktop.
Save hryk/3931291 to your computer and use it in GitHub Desktop.
an example for using boost::unordered_map in Cython.
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [
Extension("test_um",
["test_um.pyx"],
include_dirs=["/usr/local/include/boost"],
library_dirs=["/usr/local/lib"],
language="c++")
]
setup(
name="hello boost::unordered_map",
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)
from cython.operator cimport dereference as deref, preincrement as inc
from libcpp.string cimport string
from libcpp.pair cimport pair
cdef extern from "<boost/unordered_map.hpp>" namespace "boost":
cdef cppclass unordered_map[K, T]: # K: key_type, T: mapped_type
cppclass iterator:
pair& operator*()
bint operator==(iterator)
bint operator!=(iterator)
unordered_map()
bint empty()
size_t size()
iterator begin()
iterator end()
pair emplace(K, T)
iterator find(K)
void clear()
size_t count(K)
T& operator[](K)
def test():
cdef unordered_map[int, int] *v = new unordered_map[int, int]()
v.emplace(1, 1)
v.emplace(2, 2)
v.emplace(3, 100)
cdef unordered_map[int, int].iterator it = v.find(3)
return <int>deref(it).second
@maxhgerlach
Copy link

Thanks for sharing!

To use this I had to slightly change two function signatures:

cdef extern from "<boost/unordered_map.hpp>" namespace "boost":
    cdef cppclass unordered_map[K, T]: # K: key_type, T: mapped_type
        cppclass iterator:
            pair[K,T]& operator*()
            # ...
        pair[K,T] emplace(K, T)
        # ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment