Is it possible to declare and define a bit field in Cython?

Viewed 268

In C/C++ you can declare a bit field as a struct by specifying the number of bits to use for a given field in a struct. e.g.:

typedef struct {
    char threeBits : 3;
    char fiveBits : 5;
} MyBitField;

If we ask the size of this we get 1:

printf("sizeof(MyBitField): %d\n", sizeof(MyBitField)); // prints: "sizeof(MyBitField): 1"

Is it possible to define these special kind of structs in Cython?

I looked at the docs and didn't see any syntax to support this.

1 Answers

Still hoping for a better answer, but in a pinch, you can always cheat

cdef extern from *: 
    """ 
    struct MyBitField { 
        char threeBits : 3; 
        char fiveBits : 5; 
    }; 
    """ 
    cdef struct MyBitField: 
        char threeBits 
        char fiveBits 
        
cdef MyBitField mbf = MyBitField(2,3) 
print(mbf) 
print(sizeof(mbf)) 

which prints:

{'threeBits': 2, 'fiveBits': 3}
1
Related