免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3209 | 回复: 0
打印 上一主题 下一主题

Python中如何使用C的结构体struct [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-05-31 11:33 |只看该作者 |倒序浏览
在Python中导入模块struct就可以使用结构体了:
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
>: 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:char; b:signed byte;
B:unsigned byte;
h:short; H:unsigned short; i:int; I:unsigned
int;
l:long; L:unsigned long; f:float; d: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 long; Q:unsigned long long
Whitespace between formats is ignored.
如果struct模块的函数出错,将产生struct.error异常。
收到结构体的处理是类似的,只是使用unpack方法。
udata = struct.unpack( 'format_string', pack_data )
udata将是一个tuple。
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/97516/showart_1950065.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP