Wednesday, July 26, 2006

Subjective-C++

Why do I feel the need to have a witty title just because this is a blog? I feel like I'm being sucked into this whole blogging hell hole. I hate it, but I feel compelled to do it by the desire to vent my frustrations someplace other than my coworkers who I'm sure are quite sick of it.

Getting back on track, the subject of this post is Objective-C++. There is precious little literature available on the topic. The example code on Apple's site is from 2003 and does nothing of any use other than show you the proper file extension needed to compile Objective-C++ code. And the Objective-C++ section in the Objective-C manual is minimal.

The biggest resource I've found for Objective-C++ is WebKit, which is thankfully open source. I learned this through an ObjC mailing list via a helpful pointer from Michael Ash. Perusing through the source was invaluable to the work I am doing. I thought I'd start off by sharing some tips on wrapping C++ objects in Objective-C.

One thing you might want to do if you're mixing C++ and Objective-C is wrap your C++ objects so that the rest of your Cocoa app can use them without changing everything to a .mm file. Now this ObjC object will need to contain a pointer to your C++ object and your header will look something like this.

#include "CppClass.h"

@interface ObjCWrapper : NSObject {
CppClass *m_cppObject;
}
- (CppClass*)cppObject;
- (id)wrapperMethod;
...
@end

As you might have noticed, if you try to include this in an Objective-C file, the compiler will yell at you and you might start pulling all your hair out (which may or may not have happened to me) thinking it might be impossible to have a clean separation of programming languages. Well after digging through the WebKit code, I came across several headers that had something like this in place of the #include.

#ifdef __cplusplus
class CppClass;
#else
@class CppClass;
#endif

What we're doing is forward declaring the class which is great since we don't have to include the C++ header file. But what's counter-intuitive is that if this file gets included in an Objective-C file, the CppClass is forward declared as an Objective-C class. I suppose the reason that this is ok that you only reference the CppClass from within your wrapper class. As long as you don't try to use the object from within pure Objective-C code, you'll be golden.

1 Comments:

Anonymous Anonymous said...

This comment has been removed by a blog administrator.

6:00 PM  

Post a Comment

<< Home