How to use a dictionary in Cython?

Hi all,
I wonder how do you use a dictionary in Cython. I mean only in cython. No need to use it in Python world. I want to use a dictionary with HWND key and MyClass value. Is it possible ?

Assuming you followed my advice from here https://groups.google.com/g/cython-users/c/-hvFHKxxklc/m/V_Mowvo_BAAJ on how to store HWND in Cython:

I think you have two options:

  1. Convert the handles to/from integers (by casting to uintptr_t before you return them). This isn’t hugely type-safe since it lets you mix up different types of handle.

  2. Create a cdef class that wraps each type of handle and return that.

If you picked option 1 then you should already be able to store the integer in a Python dict. If you picked option 2 then the cdef class needs to have the appropriate operators to go in a dict (__hash__ and __eq__). For __hash__ you can probably just return the HWND key cast to an integer,

There may be a third option depending on what MyClass is: you could use a c++ std::map. I suspect HWND should already be suitable for use in a map (it needs to be <- and ==-comparable). However, this isn’t possible if MyClass is a Python type (including a Cython cdef class) since the c++ map will not be able to do the reference counting.

@ Da Woods,
Hi, thanks for the reply. I choose cython for performance. But I think this conversion time will slow down the the speed I gain from cython. Form you answer, I think option 1 is safe. I don’t know what will be the execution speed if I choose option 2. I can wrap the HWND type in a cdef class.