Le 20 mars 08 à 16:04, Dave Carrigan a écrit :


On Mar 20, 2008, at 6:48 AM, Sherm Pendley wrote:
On Thu, Mar 20, 2008 at 9:25 AM, Nick Rogers <[EMAIL PROTECTED]> wrote:

Hi
I'm using memcpy to copy a file's sector to my struct.
But its skipping one UInt16 in between and copying the next value in
the struct's corresponding field.
I've checked the read sector and its correctly read. My struct is
also in order.
Listing:
memcpy(&myStruct, sector, sizeof(myStruct));

What could be wrong here.
Any ideas?


Structs can have padding added to them in between members. This is most often the case when a larger member follows a smaller one, to allow the larger one to be aligned along a 4-byte or other boundary in memory. On some
architectures, memory access is faster when it's aligned this way.


The general rule - only to be broken if you absolutely know what you're doing - is that you should never serialize or unserialize structs as a block unless you know for sure that the exact same compiler, right down to the version number and compiler flags, did the serializing as did the unserializing. That generally means that unless the serializing and unserializing code is in the same compilation unit, you cannot read structs as a block and guarantee that it will work as expected. You have to read each field in the struct individually.

--
Dave Carrigan
[EMAIL PROTECTED]
Seattle, WA, USA

You can also force the struct layout, i.e. __attribute__((packed)). It will not solve the byte order issue, but it may be usefull in some rare occasions.





_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [EMAIL PROTECTED]

Reply via email to