Objective C++ Exception Handling

Pierre Thibault p.thibault at bigfoot.com
Fri Jan 25 19:52:01 PST 2002


Le vendredi 25 janvier 2002, à 11:32 AM, Pierre Thibault a écrit :

> I can try to catch Objective-C exceptions as early as possible but I 
> can only do that with my own code. What I want is a way to call those 
> C++ destructors in NS_HANDLER. Is it possible to do that? Is there 
> another solution?
>

I found what I think is a good solution to this problem. First I made 
two macros:

//-------------------------
#define DefineInterfaceForCppClass(ObjCClass, CClass) \
@interface ObjCClass : NSObject \
{ \
     CClass *object; \
} \
\
- (id) init; \
- (CClass *) object; \
- (void) dealloc; \
@end

#define DefineImplementationForCppClass(ObjCClass, CClass) \
@implementation ObjCClass \
- (id) init { [super init]; object = new CClass; return self; } \
- (CClass *) object { return object; } \
- (void) dealloc { delete object; [super dealloc]; } \
@end
//-------------------------

So this is an Objective C wrapper for a C++ class. So I can create an 
Objective C class interface for a C++ class like this:

//-------------------------
DefineInterfaceForCppClass(ObjCClassWrapper, ACppClass)
//-------------------------

And a its implementation like this:

//-------------------------
DefineImplementationForCppClass(ObjCClassWrapper, ACppClass)
//-------------------------

And later, in my code, I can use my C++ class like this:

//-------------------------
ObjCClassWrapper *myWrapper = [[[ObjCClassWrapper alloc] init] 
autorelease];
ACppClass &aCppObject = *[myWrapper object];

aCppObject is C++ object of type ACppClass that I can use freely.
//-------------------------

Now if I raise an NSException and catch it, the wrapper object will be 
destroyed with the C++ object wrapped in it.

And if a C++ exception is thrown, I will catch it and raise an 
NSException and catch it too so Objective C objects will be destroyed 
too including the wrapper objects. Note that C++ objects wrapped using 
this method are not destroyed by C++ exceptions because they are created 
dynamically.

These two macros are only good for C++ classes with a single default 
constructor but if the needs are more complex at that level, I think 
that it is better to create the interfaces and the implementations of 
the wrappers by coding them manually.

Voilà!

--------------
Pierre
p.thibault at bigfoot.com




More information about the MacOSX-dev mailing list