我刚开始使用 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/