c++c++11cythonenum-class

Wrap enum class with Cython


I am trying to wrap an enum class in a c++ header file for use in a cython project.

For example, how can this

enum class Color {red, green = 20, blue};

be wrapped with Cython.


Solution

  • The latest cython (3.x) has a direct support for c++ enum class, it's documented here: https://cython.readthedocs.io/en/latest/src/userguide/wrapping_CPlusPlus.html#scoped-enumerations

    Here is an example:

    // cpp header
    enum class State: int
    {
        Good,
        Bad,
        Unknown,
    };
    
    
    const char* foo(State s){
        switch (s){
            case State::Good:
                return "Good";
            case State::Bad:
                return "Bad";
            case State::Unknown:
                return "Unknown";
        }
    }
    

    Cython's side

    cdef extern from "test.h":
        cpdef enum class State(int):
            Good,
            Bad,
            Unknown,
    
        const char* foo(State s)
        
    def py_foo(State s):
        return foo(s)
    

    call py_foo(State.Good) returns b'Good'