Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cython: Nesting a union within a struct

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.

like image 990
polerto Avatar asked Sep 17 '12 01:09

polerto


People also ask

Can you declare struct and union one inside another?

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.

How do you use a struct union?

// 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.


2 Answers

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.

like image 126
Haldean Brown Avatar answered Sep 21 '22 20:09

Haldean Brown


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.

like image 22
nneonneo Avatar answered Sep 21 '22 20:09

nneonneo