我刚刚开始使用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;
};
Run Code Online (Sandbox Code Playgroud)
Thx,如果其他人正在寻找相同的答案,则添加简单示例
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 = …Run Code Online (Sandbox Code Playgroud) 我有以后的代码,它最终导致分段错误.
import ctypes
from random import randint
class STRUCT_2(ctypes.Structure):
#_pack_=2
_fields_ = [('field_1', ctypes.c_short),
('field_2', ctypes.c_short),
('field_3', ctypes.c_short)]
class STRUCT_1(ctypes.Structure):
#_pack_=2
_fields_ = [('elements', ctypes.c_short),
('STRUCT_ARRAY', ctypes.POINTER(STRUCT_2))]
def __init__(self,num_of_structs):
elems = (ctypes.POINTER(STRUCT_2) * num_of_structs)()
self.STRUCT_ARRAY = ctypes.cast(elems,ctypes.POINTER(STRUCT_2))
self.elements = num_of_structs
for num in range(0,num_of_structs):
self.STRUCT_ARRAY[num].field_1 = 1
self.STRUCT_ARRAY[num].field_2 = 2
self.STRUCT_ARRAY[num].field_3 = 3
for num in range(0,100):
test = STRUCT_1(num)
print "%i done" % num
Run Code Online (Sandbox Code Playgroud)
输出:5完成分段故障
但是如果struct_2中没有field_3那么它似乎正常工作.如果我添加一个短字段(field_4),它会结束分段错误...
那么我做错了什么或我错过了什么?
还有其他方法来定义数组大小吗?
所以我有两个简单的 ctypes 结构
class S2 (ctypes.Structure):
_fields_ = [
('A2', ctypes.c_uint16*10),
('B2', ctypes.c_uint32*10),
('C2', ctypes.c_uint32*10) ]
class S1 (ctypes.Structure):
_fields_ = [
('A', ctypes.c_uint16),
('B', ctypes.c_uint32),
('C', S2) ]
Run Code Online (Sandbox Code Playgroud)
例如,是否可以使用namedtuple 执行相同的操作?nametuple 中如何处理列表?
编辑:
结构包用法
test_data = '0100000002000000' + 10*'01' + 10*'01' + 10*'01'
S2 = collections.namedtuple('S2', ['A2', 'B2', 'C2'])
S1 = collections.namedtuple('S1', ['A', 'B', 'REF_to_S2'])
Data2 = S2._make(struct.unpack('10p10p10p', binascii.unhexlify(test_data[16:])))
##this is not working, because there must be 3 args..
Data1 = S1._make(struct.unpack('ii', binascii.unhexlify(test_data[0:16])))
Run Code Online (Sandbox Code Playgroud)
最后我想以可读格式打印数据(具有可见的键:值对)。但现在我不知道应该如何处理两个不同的命名元组的解包操作......?
这个 unpack.struct 操作会处理值类型问题,对吗?