Objective-C Wrappers for C++ Classes

February 5th, 2010

I read the Apple document Using C++ With Objective C. Even so, I had some trouble creating an Obj-C wrapper for a C++ class. Here are the key points to how I finally did it:

- Obj-C class contains pointer to wrapped C++ class
- Obj-C wrapper class header has a tricky #ifdef so that the header compiles for .mm and .m files
- Instantiate C++ class in Obj-C init method
- Use the right NSString conversion functions for parameter passing and returns

Here’s the source code for the wrapper .mm and .h files:

Wrapper.h:

#import

// declare C++ implementation for .mm (Obj-C++) files
#ifdef __cplusplus
class CImplement;
#endif

// declare C++ implementation for .m (Obj-C) files
#ifdef __OBJC__
#ifndef __cplusplus
typedef void CImplement;
#endif
#endif

@interface Wrapper : NSObject {
CImplement* mImplement;
}

- (id)init:(bool)boolParam:(int)intParam;
- (NSString*)getStringVal;
- (void)setStringVal:(NSString*)strParam;

@end

Wrapper.mm:

#import "Wrapper.h"

// C++ class (define here ore include header)
class CImplement
{
public:
CImplement(bool boolParam, int intParam)
{
// do something
}

const char* getSomething(void)
{
return "something";
}

void setSomething(const char* s)
{
// set something
}
};

@implementation Wrapper

// initialization
- (id)init:(bool)boolParam:(int)intParam
{
[super init];
mImplement = new CImplement(boolParam, intParam);
return self;
}

// method that takes a string
- (void)setStringVal:(NSString*)str
{
mImplement->setSomething([str UTF8String]);
}

// method that returns a string
- (NSString*)getStringVal
{
return [NSString stringWithUTF8String:mImplement->getSomething()];
}

@end