python - 如何在 python 中使用联合?

标签 python union ctypes

我刚开始使用 python,我想知道我应该如何使用 python 定义联合(使用 ctypes)?希望我是对的,通过 ctypes 支持联合。例如下面的 c 代码在 python 中是怎样的

struct test
{
char something[10];
int status;
};

struct test2
{
char else[10];
int status;
int alive;
};

union tests
{
struct test a;
struct test2 b;
};

struct tester
{
char more_chars[20];
int magic;
union tests f;
};

谢谢,如果其他人正在寻找相同的答案,则添加简单示例

from ctypes import *

class POINT(Structure):
    _fields_ = [("x", c_int),
                 ("y", c_int)]

class POINT_1(Structure):
    _fields_ = [("x", c_int),
                 ("y", c_int),
                 ("z",c_int)]

class POINT_UNION(Union):
    _fields_ = [("a", POINT),
                 ("b", POINT_1)]

class TEST(Structure):
    _fields_ = [("magic", c_int),
                 ("my_union", POINT_UNION)]

testing = TEST()
testing.magic = 10;
testing.my_union.b.x=100
testing.my_union.b.y=200
testing.my_union.b.z=300

最佳答案

看看 ctypes tutorial .您使用 ctypes.Union 类:

class test(ctypes.Structure):
    # ...
class test2(ctypes.Structure):
    # ...

class tests(ctypes.Union):
    _fields_ = [("a", test),
                ("b", test2)]

关于python - 如何在 python 中使用联合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13293703/

相关文章:

python - 使用用户输入打印数学: Can't convert float to str implicitly

mysql order by with union 似乎不起作用

mysql - 优化联盟请求

python - 使用 ctypes 将 python 字符串传递给 Fortran 子例程

python - 用 ctypes 替换共享库中的函数指针

python - 在 python 文件夹中导入图表/结构(清理代码)

python - 在列表中查找特定的子列表

Python 内部类计数器

使用 UNION 获取的数据数组的 MySQL 键名

Python:获取和保存屏幕截图的最快方法