Cython:在stru中嵌套一个union

2024-10-03 11:13:08 发布

您现在位置:Python中文网/ 问答频道 /正文

在cythonglue声明中,如何表示包含匿名联合的Cstruct类型?例如,如果我有一个包含

struct mystruct
{
    union {
        double da;
        uint64_t ia;
    };
};

然后,在相应的.pyd文件中

^{pr2}$

我试过了:

cdef extern from "mystruct.h":
    struct mystruct:
        union {double da; uint64_t ia;};

但这只给了我union行的“C变量声明中的语法错误”。在


Tags: 文件声明类型structdapyddoubleunion
2条回答

据我所知,你不能嵌套声明,而且Cython根本不支持匿名联合。在

尝试以下操作:

cdef union mystruct_union:
    double lower_d
    uint64_t lower

cdef struct mystruct:
    mystruct_union un

现在以un.lower_dun.lower的形式访问联合成员。在

对于那些通过谷歌来到这里的人,我找到了解决办法。如果你有一个结构:

typedef struct {
    union {
        int a;
        struct {
            int b;
            int c;
        };
    }
} outer;

你可以在Cython声明中把它弄平,就像这样:

^{pr2}$

Cython生成的代码不会对结构的内存布局做出任何假设;您只是告诉它要生成什么样的语法来调用它,从而告诉它实际的调用结构。因此,如果您的结构有一个大小为int的成员,可以作为((outer) x).a访问,那么您可以在结构定义上抛出a,它就可以工作了。它操作的是文本替换,而不是内存布局,所以它不关心这些东西是在匿名联合还是在结构中,或者是什么。在

相关问题 更多 >