Re: Reading Adobe Photoshop header, Obj-C
Re: Reading Adobe Photoshop header, Obj-C
- Subject: Re: Reading Adobe Photoshop header, Obj-C
- From: Charles Srstka <email@hidden>
- Date: Tue, 28 Jun 2011 14:37:57 -0500
On Jun 28, 2011, at 12:00 PM, Jens Alfke wrote:
> Another way (that I often use) is to define a C struct that matches the fields and layout of the header, then cast the bytes to a pointer to that struct and read the fields. It makes your code look a lot cleaner, but you have to be careful to (a) make sure the compiler packs the struct fields properly, and (b) you byte-swap all integer/float fields appropriately.
It’s my understanding that reading/writing a struct directly to/from a file is considered poor practice, because of the two things you mentioned: endian issues, and the fact that you don’t know how the compiler will align the fields — and even if you test that, you don’t know that it’s not going to change in some future version of clang or gcc, or that Apple’s not going to switch to a new architecture or something in which the compilers will emit different output.
Anyway, you have to go through the struct endian-swap all the fields anyway, so why not just read in the fields individually in the first place? I recommend something similar to the code sample you provided above, but instead of using NSSwapBigShortToHost(), I prefer to use the CF byte-swapping functions instead, as they allow you to specify the actual size of the data you’re reading instead of making assumptions about the sizes of short, long, etc. If the size of ‘short’ changes from 16 to 32 bits in some future architecture change, for instance, as ‘long’ changed from 32 to 64 bits in the x86_64 transition, that code using NSSwapBigShortToHost() will break. Using, for example, CFSwapInt16BigToHost() instead of NSSwapBigShortToHost() will make sure your code works no matter what architecture it happens to be running on.
Charles_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden