One of the first decisions I made for coding on iOS was that I need to keep a bunch of code portable so I can jump in with Windows versions of things if needs be. That will mainly be for games, but when you have a strict MVC pattern it’s easy enough to put the model out into a separate language.
Luckily Xcode allows you to mix and match languages inside of the same project. Visual Studio would require me to put the C++ code into a different assembly if I wanted to use it with C# so in the end it’s slightly better than that. The slight problems are that it means that you need to get the two languages to coexist.
The problem I face is one akin to the managed and unmanaged code in Managed C++ for .NET. Obj-C has a layer of functionality that means that just consuming the C++ object is not going to work. A wrapper is needed in order to bridge between the two. Say I was going to wrap a nice C++ class that contains some nice cross platform graphics code I need something like this:
@interface OpenGLView : NSOpenGLView
{
Wrapper *openGL;
}
-(void)drawRect:(NSRect)dirtyRect
{
if(openGL == nil)
{
openGL = [[Wrapper alloc]init];
}
[openGLInitScene];
[openGL Draw];
}
I’m not sure that the lazy allocation of the object there is a good idea, but it works for now. Wrapper is an Obj-C class that looks like this:
Wrapper.h
#ifdef __cplusplus
class OpenGLBase;
#endif
#ifdef __OBJC__
#ifndef __cplusplus
typedef void OpenGLBase;
#endif
#endif
@interface Wrapper : NSObject
{
OpenGLBase* openGL;
}
-(void)Draw;
-(void)InitScene;
@end
Wrapper.mm
#import “Wrapper.h”
#include “OpenGLBase.h”
@implementation Wrapper
-(id)init
{
self = [super init];
openGL = new OpenGLBase();
return self;
}
-(void)Draw
{
openGL->Draw();
}
-(void)InitScene
{
openGL->InitScene();
}
@end
They key thing to notice is that the file is called Wrapper.mm instead of just Wrapper.m as that enables the object oriented features and allows a C++ class to even get close to it.
Now this solution does not seem neat to me by any means. There’s some serious redundancy in having Obj-C functions that just call through to the C++ object that could be a real mess for maintenance and I’ve not looked at any performance implications that they may have either. If the interface between the two is a small number of member functions then I’m not going to be too concerned for now, it works and allows me to bridge the gap. I can find a better solution when I know Obj-C better. I’m sure I can do something with interfaces to force me to implement functions or something, just as I would with an abstract base class in C++ or an interface in any other language. That is for the future, for now I have some working code I can use for playing around with OpenGL.