[Newbies] Reading and writing C structs

David T. Lewis lewis at mail.msen.com
Sat May 24 01:17:37 UTC 2008


On Fri, May 23, 2008 at 02:10:58PM -0700, David Finlayson wrote:
> An instrument I am working with creates a complicated binary file
> (memory dumps of C structs). I would like to try reading the file into
> Squeak for a cool new project. What's the best way to set up and read
> C-based structs and then, once I'm done, to write them back out again
> (including endianness, padding bytes and all the other nonsense)? I
> could use pointers to related classes as well if they are
> needed/useful for working with primitive types like this. An example
> would be great.
> 
> I found that there are some interesting methods in PositionableStream
> for reading and writing integer types from a binary stream. Is this
> where I should start? What about floats and doubles? This seems a bit
> low-level, but I could work with it. I'm a so-so C programmer with
> experience in Python, but still learning Smalltalk.

David,

Look at the Number class hierarchy (browse hierarchy) and look at the
"instance creation" category on the class side of each of these classes.
That will give you some good tips. If you are dealing with simple data
structures on a single machine architecture, this will not be too
difficult.

However:

The binary image of C data structures is inherently non-portable. The
compiler may pad data to different positions, the byte ordering may
vary on different hardware, and even simple data types can have different
sizes and byte orderings from one operating system to another. If you
are dealing with floating point data types, it's even trickier.

I don't know what instrument you are dealing with, but if there is
a way to get it to produce data in a more platform-independent manner,
that may save you some aggrivation in the long run.

Dave



More information about the Beginners mailing list