蟒蛇ctypes的杂包字节对齐的读 [英] python ctypes pragma pack for byte aligned read
问题描述
我有一个C ++应用程序下面的结构写入文件。现在我需要使用Python来解组他们,这里的基本问题是如何体现杂包
在python选项。
I have a C++ application with below structure written to file. Now I need to unmarshal them using python, The basic problem here is how to reflect the pragma pack
option in python.
C ++结构
#pragma pack(1)
struct abc
{
unsigned char r1;
unsigned char r2;
unsigned char p1;
unsigned int id;
};
#pragma pack()
现在,结构尺寸为 7不8
,该数据被写入到数据文件中。如何使用python我检索此数据。
Now, the structure size is 7 not 8
,this data is written into a data file. How do I retrieve this data using python.
注:
1.我使用的ctypes,和上述结构是一个示例结构。
Note :
1. I am using ctypes, and the above structure is a sample structure.
ctypes使用结构和联合本地字节顺序。要建立与非本地字节顺序结构,可以使用BigEndianStructure,LittleEndianStructure,BigEndianUnion和LittleEndianUnion中基类中的一个。这些类不能包含指针领域的
从python文档以上信息,并不深入到细节。
The above information from python docs, does not delve into details.
推荐答案
您可以如改变ctypes的包装<一href="http://docs.python.org/2/library/ctypes.html#structure-union-alignment-and-byte-order">here
You can change the packing in ctypes as described here
在默认情况下,结构和联合域排列在C编译器则用同样的方式。它可以覆盖这一行为被指定的包中的子类定义的类属性。这必须被设置为一个正整数,并指定的最大对齐的字段。这就是指令#pragma包(N)在MSVC。
By default, Structure and Union fields are aligned in the same way the C compiler does it. It is possible to override this behavior be specifying a pack class attribute in the subclass definition. This must be set to a positive integer and specifies the maximum alignment for the fields. This is what #pragma pack(n) also does in MSVC.
有关的例子,这会是:
from ctypes import *
class abc(Structure):
_pack_ = 1
_fields_ = [
('r1',c_ubyte),
('r2',c_ubyte),
('p1',c_ubyte),
('id',c_uint)]
这篇关于蟒蛇ctypes的杂包字节对齐的读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!