borrrden
borrrden

Reputation: 33421

Is NSSizeFromCGSize nothing more than a cast operation?

The source is as follows:

NS_INLINE NSSize NSSizeFromCGSize(CGSize cgsize) {
    union _ {NSSize ns; CGSize cg;};
    return ((union _ *)&cgsize)->ns;
}

To me this just looks like an overcomplicated cast (reading a chunk of memory differently than originally intended). Is there a reason that this syntax is needed? I only ask because I've never seen this before.

Upvotes: 0

Views: 168

Answers (1)

CRD
CRD

Reputation: 53000

Yes, this is effectively a cast. In C, and hence Objective-C, you cannot cast one structure type to another - which in general is a good thing! However you can cast a pointer to anything to a pointer to anything else - which in general is dangerous...

So if, and only if, you really know two structures are identical you can cast the value from a variable of one structure type to a value of the other structure type by taking the address of the variable (&cgsize), casting the resultant pointer ((union _ *)), and then dereferencing the pointer (->ns) to get the type cast value. Any decent compiler will optimize this away and do a straight copy of the value.

Upvotes: 1

Related Questions