Consider how to access, in Cython, the following C++ static inline class member variable:
namespace my::name::space
{
class MyClass
{
public:
static inline int LIFE { 42 };
};
}
A plausible .pyx
file might be:
cdef extern from "mycpp.h" namespace "my::name::space":
cdef cppclass MyClass:
int LIFE
cdef class MyMgr:
def my_failing_function(self) -> None:
cdef int life = MyClass.LIFE
But this elicits the following diagnostic during generated C++ compilation:
src/dotbug/dotbug-mre.cpp: In function ‘PyObject* __pyx_pf_6dotbug_5MyMgr_my_failing_function(__pyx_obj_6dotbug_MyMgr*)’:
src/dotbug/dotbug-mre.cpp:2666:39: error: expected primary-expression before ‘.’ token
2666 | __pyx_t_1 = my::name::space::MyClass.LIFE;
| ^
This is not valid C++ syntax; the period should be the scoping operator, ::
. If you change it in the generated code, and build, it works properly.
ChatGPT recommended (before it broke down and claimed Cython cannot access static member variables) that I use static int LIFE
for my cdef definition, but this yields a different error, this one during cythonization:
cdef extern from "mycpp.h" namespace "my::name::space":
cdef cppclass MyClass:
static int LIFE
^
------------------------------------------------------------
src/dotbug/dotbug-mre.pyx:3:19: Syntax error in C variable declaration
Is there something I am missing with respect to syntax? I note that if I convert this into a non-static variable, and instantiate it, I can access it just fine.
For a full set of buildable files, see Github Gist
Consulting experts and ChatGPT, there seems to be no way to declare this properly in Cython, but there is an effective workaround that generates valid code, by using the class as a namespace and declaring the member variable within it:
cdef extern from "mycpp.h" namespace "my::name::space::MyClass":
int LIFE
cdef class MyMgr:
def my_failing_function(self) -> None:
cdef int life = LIFE