In Cython glue declarations, how do I represent a C struct
type containing an anonymous union? For example, if I have a C header file mystruct.h
containing
struct mystruct
{
union {
double da;
uint64_t ia;
};
};
then, in the corresponding .pyd
file
cdef extern from "mystruct.h":
struct mystruct:
# what goes here???
I tried this:
cdef extern from "mystruct.h":
struct mystruct:
union {double da; uint64_t ia;};
but that only gave me "Syntax error in C variable declaration" on the union
line.
A structure can be nested inside a union and it is called union of structures. It is possible to create a union inside a structure.
// Anonymous union example union { char alpha; int num; }; // Anonymous structure example struct { char alpha; int num; }; Since there is no variable and no name, we can directly access members. This accessibility works only inside the scope where the anonymous union is defined.
For those who got here via Google, I found a solution to this. If you have a struct:
typedef struct {
union {
int a;
struct {
int b;
int c;
};
}
} outer;
You can flatten it all out in the Cython declaration, like so:
ctypedef struct outer:
int a
int b
int c
Cython isn't generating any code that makes any suppositions about the memory layout of your struct; you're only telling it the de facto structure of what you're calling by telling it what syntax to generate to call it. So if your structure has a member of size int
that can be accessed as ((outer) x).a
, then you can throw a
on the struct definition and it will work. It's operating on textual substitution, not memory layout, so it doesn't care about whether these things are in anonymous unions or structs or what have you.
You can't nest declarations to the best of my knowledge, and Cython doesn't support anonymous unions AFAIK.
Try the following:
cdef union mystruct_union:
double lower_d
uint64_t lower
cdef struct mystruct:
mystruct_union un
Now access the union members as un.lower_d
and un.lower
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With