Re: Help Mixing Objective-C & Objective-C++
Re: Help Mixing Objective-C & Objective-C++
- Subject: Re: Help Mixing Objective-C & Objective-C++
- From: Ken Thomases <email@hidden>
- Date: Wed, 23 Feb 2011 13:41:41 -0600
On Feb 23, 2011, at 12:55 PM, Sean McBride wrote:
> 2) You can keep C++ out of your Obj-C .h files like so:
>
> #ifdef __cplusplus
> typedef SomeCPPClassPtr SomeCPPClassRef;
> #else
> typedef void* SomeCPPClassRef;
> #endif
It might be better to follow the pImpl (pointer-to-implementation) pattern. The interfaces which need to wrap C++ functionality but be imported to Objective-C code would not put any implementation detail (like the real instance variables) into the interface. Instead, the interface would have a single instance variable, a pointer to the implementation data. In the interface, the pointer type is opaque. It only gets defined in the implementation.
One possibility is to use an id and have the interface wrap a private Objective-C++ class. Another is to have it be a forward-declared struct pointer. (Remember that, in C++, a struct is just a class whose members are public by default.) A third is to have it be a void pointer.
For an example of where Apple has done this, look at /System/Library/Frameworks/Foundation.framework/Headers/NSOperation.h. Note the minimal instance variables exposed in the interface.
So, for example:
// Foo.h
@interface Foo : NSObject {
struct FooPrivate* priv;
}
// ... methods ...
@end
// Foo.mm
struct FooPrivate {
// Implementation instance variables, including C++ stuff
// May include member functions, too.
};
@implementation Foo
- (id) init
{
self = [super init];
if (self != nil)
{
priv = new FooPrivate;
// ... fill in the priv struct ...
}
return self;
}
- (void) dealloc
{
delete priv;
[super dealloc];
}
// ... methods ...
@end
// Bar.m
#import "Foo.h"
// ... use Foo class ...
Regards,
Ken
_______________________________________________
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