How to expose a constexpr to Cython?

2019-07-01 09:07发布

问题:

A file Globals.h contains the following definition of a constant:

namespace MyNameSpace {

/** Constants **/
constexpr index none = std::numeric_limits<index>::max();

}

... where index is a typedef for uint64_t.

How can I expose it to Cython and Python?

A failed attempt:

cdef extern from "../cpp/Globals.h" namespace "MyNamespace":
    cdef index _none "MyNamespace::none"

none = _none

回答1:

The syntax for exposing (global) constants is similar to the syntax for exposing simple attributes and the syntax for exposing static members, in your example the syntax is almost right except that you need to omit the cdef statement, the cdef statement is only for declaring new variables in Cython, not for adding information about externally declared variables.

cdef extern from "../cpp/Globals.h" namespace "MyNamespace":
    index _none "MyNamespace::none"

none = _none

Then you can use none in Python, if your Cython module is named mymodule, the import statement could be

from mymodule import none

if you want to make none available as global name in your Python code.