TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Python: Making ctypes Structures Beautiful

44 点作者 they4kman将近 13 年前

4 条评论

densh将近 13 年前
People never seem to fully understand namespaces. You don't need any additional prefixes for classes and functions inside of your module. Its name already does separate it from everything else. Moreover "from module import *" is evil. Period.<p>import newstruct as ns<p>...<p>x = ns.long()
评论 #4238145 未加载
jessedhillon将近 13 年前
<i>That's my module. Now, how can I make it better?</i><p>You could have those fields know their own sizes, and then you could have Struct subclasses know the size of their instances, so you don't have to call sizeof. E.g.:<p><pre><code> class DataHeader(Struct): address = newstruct.long() typ = newstruct.byte() tag = newstruct.short() data = newstruct.byte(length=40) # 40 bytes &#62;&#62;&#62; fp = open('mydata', 'rb') &#62;&#62;&#62; dh = DataHeader.read(fp) # or perhaps: DataHeader.load(fp.read(len(dh))) # this way the side-effect of moving fp's current position is more explicit &#62;&#62;&#62; fp.close() &#62;&#62;&#62; len(dh) 12345 # or whatever, sum of sizes for long, 41 bytes, and short</code></pre>
评论 #4236323 未加载
jevinskie将近 13 年前
My go-to library for binary mucking in Python is the <i>fantastic</i> Construct library. [0] [1] It is a declarative way of specifying binary structures. It handles endianness, serialization, and deserialization for you. You can build structures of structures with Construct. I used it to parse the PS3's pseudo-ELF files (SELFs) and was quite successful except for a few shortcomings in the library. I don't blame Construct though because the SELF format is a wild beast. Corbin Simpson (the author) was quite helpful when I was looking into the possibility of fixing my issues. Look at the ELF parser to see how easy it is to use! [2]<p>[0]: <a href="http://construct.readthedocs.org/en/latest/" rel="nofollow">http://construct.readthedocs.org/en/latest/</a><p>[1]: <a href="https://github.com/construct/construct" rel="nofollow">https://github.com/construct/construct</a><p>[2]: <a href="https://github.com/construct/construct/blob/master/construct/formats/executable/elf32.py" rel="nofollow">https://github.com/construct/construct/blob/master/construct...</a>
wisesage5001将近 13 年前
One thing I really like about the struct module's format string is the ability to easily specify the endian-ness of the data. How does newstruct (or the underlying ctypes) handle endian-ness (if at all)?
评论 #4236045 未加载