Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Wrapping CPP map container to a dict-like Python object

View map_wrapper.pyx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
"""
Uses C++ map containers for fast dict-like behavior with keys being
integers, and values float.
"""
# Author: Gael Varoquaux
# License: BSD
 
# XXX: this needs Cython 17.1 or later. Elsewhere you will get a C++ compilation error.
 
import numpy as np
 
# Import the C-level symbols of numpy
cimport numpy as np
 
# Numpy must be initialized. When using numpy from C or Cython you must
# _always_ do that, or you will have segfaults
np.import_array()
 
DTYPE = np.float64
ctypedef np.float64_t DTYPE_t
 
ITYPE = np.int32
ctypedef np.int32_t ITYPE_t
 
from libcpp.map cimport map as cpp_map
 
###############################################################################
# An object to be used in Python
 
cdef class IntFloatDict:
cdef cpp_map[ITYPE_t, DTYPE_t] my_map
 
def __init__(self, np.ndarray[ITYPE_t, ndim=1] keys,
np.ndarray[DTYPE_t, ndim=1] values):
cdef cpp_map[ITYPE_t,DTYPE_t] my_map
cdef int i
cdef int size = values.size
# Should check that sizes for keys and values are equal, and
# after should boundcheck(False)
for i in range(size):
my_map[keys[i]] = values[i]
self.my_map = my_map
 
def __len__(self):
return self.my_map.size()
 
def __getitem__(self, int key):
return self.my_map[key]
 
def __setitem__(self, int key, float value):
self.cpp_map[key] = value
 
# XXX: Need a __dealloc__ to clear self.cpp_map

Note that self.my_map = my_map copies the entire map. If you make my_map a reference and skip the assignment, it should work without the copy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.