TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Python: Making ctypes Structures Beautiful

44 pointsby they4kmanalmost 13 years ago

4 comments

denshalmost 13 years ago
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 未加载
jessedhillonalmost 13 years ago
<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 未加载
jevinskiealmost 13 years ago
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>
wisesage5001almost 13 years ago
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 未加载