Wrap enum class for cython

后端 未结 3 1676
面向向阳花
面向向阳花 2021-01-02 03:15

I am trying to wrap an enum class in a c++ header file for use in a cython project.I have googled around and can not find out how to achieve this - is it supported?

3条回答
  •  星月不相逢
    2021-01-02 03:54

    Here's an alternative solution that uses the ability to change the name of cython and C++ identifiers.

    header.hpp

    namespace foo {
    enum class Bar : uint32_t {
        BAZ,
        QUUX
    };
    }
    

    header.pxd

    cdef extern from "header.hpp" namespace "foo::Bar":
        cdef enum Bar "foo::Bar":
            BAZ,
            QUUX
    

    main.pyx

    from header cimport *
    cdef void doit(Bar b):
        pass
    
    doit(BAZ) # Not Bar.BAZ, which would have been nicer.
    

    It's effectively telling cython that there exists a namespace called "foo::Bar", and puts a C-style enum in it. To counteract the fact that Bar would otherwise become "foo::Bar::Bar" that is also given an overridden name. It does mean that Bar::BAZ is referred to as BAZ in cython, rather than Bar.BAZ which would be a more idiomatic representation of enum classes, but it seems close enough.

提交回复
热议问题