Custom struct hash functions

79 views
Skip to first unread message

Peter

unread,
Oct 9, 2012, 9:51:18 AM10/9/12
to cython...@googlegroups.com
I'm attempting to store a struct in an unordered_set. In order to do this, I'm trying to provide a custom hash function.

Obviously, this is not the correct way of doing it:

cdef struct Name:
      string first
      string last
      cdef size_t operator() (Name &name):
                 return hash[string](name.first + name.second)

It gives me a "Syntax error in C variable declaration" error. Without the "cdef" I get an "C function definition not allowed here" exception.

What would be the right way to do this?

Thanks :)

Joshua Landau

unread,
Oct 9, 2012, 2:54:33 PM10/9/12
to cython...@googlegroups.com
On 9 October 2012 14:51, Peter <pna...@dataraker.com> wrote:
I'm attempting to store a struct in an unordered_set. In order to do this, I'm trying to provide a custom hash function.

Obviously, this is not the correct way of doing it:

cdef struct Name:
      string first
      string last
      cdef size_t operator() (Name &name):

I'm no expert, but are you meant to have two pairs of braces?

Robert Bradshaw

unread,
Oct 9, 2012, 4:37:00 PM10/9/12
to cython...@googlegroups.com
There are a couple of issues. First, you have to declare this as a c++
class not a struct (structs are for method-less C structs). You have
to enable the experimental_cpp_class_def directive to do this. Then
there's the question of how hash is defined, you might have to do

cdef extern from *:
cdef size_t hash_string "hash<string>"(string)

as Cython doesn't know about C++ template functions (yet). At this
point you might be better off defining this tiny class in an auxiliary
C++ file... (I'd like to support this, but we also want to avoid
Cython morphing into a full superset of C++. This boils down to the
general problem that C libraries are easy to use from other languages,
but C++ ones not so much.)

- Robert
Reply all
Reply to author
Forward
0 new messages