import struct
生成一个结构体实例:
data = struct.pack( 'format_string', struct_menber_1, struct_menber_2, ... )
其中的format_string用来指定结构体的格式(指明该结构体在C中的定义),由两部分组成:
首先是一个可选的特殊字符,用来指明字节序、数据类型大小和对齐方式:
@: native order, size &alignment (default)
=: native order, std. size &alignment
<: little-endian, std. size &alignment
>: big-endian, std. size &alignment
!: same as >
然后是指明结构体定义的部分:
The remaining chars indicate types of args and must match exactly
these can be preceded by a decimal repeat count:
x: pad byte (no data)c:charb:signed byteB:unsigned byte
h:shortH:unsigned shorti:intI:unsigned int
l:longL:unsigned longf:floatd:double.
Special cases (preceding decimal count indicates length):
s:string (array of char)p: pascal string (with count byte).
Special case (only available in native format):
P:an integer type that is wide enough to hold a pointer.
Special case (not in native mode unless 'long long' in platform C):
q:long longQ:unsigned long long
Whitespace between formats is ignored.
如果struct模块的函数出错,将产生struct.error异常。
展开全部閟truct就可以使用结构体了:
import
struct
生成一个结构体实例:
data
=
struct.pack(
'format_string',
struct_menber_1,
struct_menber_2,
...
)
其中的format_string用来指定结构体的格式(指明该结构体在C中的定义),由两部分组成
况如下:打算从python发一个tcp数据包给远程服务器,数据的主体是一个c语言的
struct
(较大,size
为1402)。由于这个struct太复杂,故不打算在python
处对其重新定义,目前的想法是用python调用一个c语言的模块,在这个模块中定义这个struct,并设置好数据后,将其struct传回python中,再打包传送服务器。
但是不知道如何将这个struct
变量从c语言
传入python中。尝试用py_buildvalue函数,以py_buildvalue("p",&interface_setup)
//interface_setup为结构体变量
传递,
但是几次都得到运行时错误:
systemerror:
bad
format
char
passed
to
pybuildvaule。