On 8 Aug 2008, at 01:59, Johannes Fortmann <[EMAIL PROTECTED]> wrote:

The problem here is that UTCDateTime is defined with #pragma pack 2 in
effect. That means the compiler packs with an alignment of 2, so the
whole structure has 8 bytes. The proper alignment (4) results in 12
bytes. Since there's nothing in the @encode'd information specifying
the non-standard alignment, NSGetSizeAndAlignment (which NSValue
probably uses internally) will return 12 bytes as the struct's size.

As an example,

#include <Foundation/Foundation.h>

void main()
{
    NSUInteger size, align;
    NSGetSizeAndAlignment (@encode(UTCDateTime),
                           &size,
                           &align);
    printf("%i, %i, %s\n", sizeof(UTCDateTime), size,
@encode(UTCDateTime));
}

prints "8, 12, {UTCDateTime=SIS}".

Thank you. This explains the problems I had.

So:
        some_type a;
NSValue *data = [ NSValue value: &a withObjCType: @encode (some_type) ];
followed by:
        some_type b;
        [ data getValue: &b ];
is unsafe, dangerous and strictly to be avoided - especially if the definiton of "some_type" is buried in some frameworks.

Instead one must use:
        some_type *bPointer = [ data bytes ];
The only problem: NSValue has no method "bytes".

So we have to do:
        const char *objCType = [ data objCType ];
        unsigned int size;
        NSGetSizeAndAlignment (objCType, &size, NULL);
// The alloca() function is machine and compiler dependent; its use is discouraged. Why?
        some_type *bPointer = alloca(size);
        [ data getValue: bPointer ];
Or does anyone have a better idea?

Another question:
sizeof(UTCDateTime) < NSValue.
Now this begs the question: Can there be some bloated_type with:
sizeof(bloated_type) > NSValue ?
That is: is there some alignment pragma taking more bytes than the alignment used by NSValue?

FInal question: May the dangerous and (at least in Tiger) undocumented behaviour of getValue: be labeled as a severe design error?


Kind regards,

Gerriet.

_______________________________________________

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