cython
cython copied to clipboard
[BUG] Cannot construct struct with const members
Describe the bug This works in C:
#include <stdio.h>
struct A { const int a; };
int main() {
struct A a = {42};
printf("%d\n", a.a);
}
But not in Cython:
# cython: language_level=3
cdef struct A:
const int a
cdef A a = A(42)
print(a.a)
Sometimes we get an error by the C compiler, as in the example above:
error: cannot assign to non-static data member 'a' with const-qualified type 'const int'
__pyx_t_1.a = 42;
~~~~~~~~~~~ ^
Sometimes I get an error from the Cython compiler, unfortunately I haven't been able to come up with a minimal example:
Error compiling Cython file:
------------------------------------------------------------
...
try:
value = obj['a']
except KeyError:
raise ValueError("No value specified for struct attribute 'a'")
result.a = value
^
------------------------------------------------------------
FromPyStructUtility:20:10: Assignment to const attribute 'a'
Environment (please complete the following information): Cython version 0.29.30
My feeling is that this will be hard to fix:
- Cython currently keeps code C89 compatible. That means that it puts the declarations first and the initialization after. Obviously in this case it could be directly initialized, but that wouldn't work if it the value it was being initialized with required temps.
- For an
externstruct Cython doesn't know that the description you've given it is complete or ordered (hence wants to initialize fields by name). Obviously that doesn't apply here, but the code generation is mostly the same for extern and non-extern structures.
None of this is impossible, but I wouldn't expect this to work soon